add util to get onion address from private key (#39)

* add util to get onion address from private key

* PR comments: added test, using go-ricochet errors, function argument a privateKey

* remove unnecesary cast and variable
This commit is contained in:
Dan Ballard 2018-04-30 18:03:06 -07:00 committed by Sarah Jamie Lewis
parent 92b9a0eb1f
commit 3920d33a77
3 changed files with 29 additions and 1 deletions

View File

@ -9,6 +9,7 @@ import (
"io/ioutil"
"math"
"math/big"
"github.com/yawning/bulb/utils/pkcs1"
)
const (
@ -69,3 +70,14 @@ func PrivateKeyToString(privateKey *rsa.PrivateKey) string {
return string(pem.EncodeToMemory(&privateKeyBlock))
}
// return an onion address from a private key
func GetOnionAddress(privateKey *rsa.PrivateKey) (string, error) {
addr, err := pkcs1.OnionAddr(&privateKey.PublicKey)
if err != nil {
return "", err
} else if addr == "" {
return "", OnionAddressGenerationError
}
return addr, nil
}

View File

@ -5,6 +5,10 @@ import (
"testing"
)
const (
privateKeyFile = "./../testing/private_key"
)
func TestGeneratePrivateKey(t *testing.T) {
_, err := GeneratePrivateKey()
if err != nil {
@ -13,7 +17,7 @@ func TestGeneratePrivateKey(t *testing.T) {
}
func TestLoadPrivateKey(t *testing.T) {
_, err := LoadPrivateKeyFromFile("../testing/private_key")
_, err := LoadPrivateKeyFromFile(privateKeyFile)
if err != nil {
t.Errorf("Error while loading private key from file: %v", err)
}
@ -25,3 +29,14 @@ func TestGetRandNumber(t *testing.T) {
t.Errorf("Error random number outside of expected bounds %v", num)
}
}
func TestGetOnionAddress(t *testing.T) {
privateKey, _ := LoadPrivateKeyFromFile(privateKeyFile)
address, err := GetOnionAddress(privateKey)
if err != nil {
t.Errorf("Error generating onion address from private key: %v", err)
}
if address != "kwke2hntvyfqm7dr" {
t.Errorf("Error: onion address for private key not expected value")
}
}

View File

@ -40,6 +40,7 @@ const (
// Library Use Errors
PrivateKeyNotSetError = Error("ClientFailedToAuthenticateError")
OnionAddressGenerationError = Error("OnionAddressGenerationError")
// Connection Errors
ConnectionClosedError = Error("ConnectionClosedError")