diff --git a/utils/crypto.go b/utils/crypto.go index 7e0cbd0..cec7874 100644 --- a/utils/crypto.go +++ b/utils/crypto.go @@ -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 +} \ No newline at end of file diff --git a/utils/crypto_test.go b/utils/crypto_test.go index 504d01b..e827f5c 100644 --- a/utils/crypto_test.go +++ b/utils/crypto_test.go @@ -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") + } +} diff --git a/utils/error.go b/utils/error.go index 4eb2475..e49d010 100644 --- a/utils/error.go +++ b/utils/error.go @@ -40,6 +40,7 @@ const ( // Library Use Errors PrivateKeyNotSetError = Error("ClientFailedToAuthenticateError") + OnionAddressGenerationError = Error("OnionAddressGenerationError") // Connection Errors ConnectionClosedError = Error("ConnectionClosedError")