diff --git a/openssl.go b/openssl.go index 181da2b..e0327be 100644 --- a/openssl.go +++ b/openssl.go @@ -70,14 +70,21 @@ func (o *OpenSSL) decrypt(key, iv, data []byte) ([]byte, error) { } // EncryptString encrypts a string in a manner compatible to OpenSSL encryption -// functions using AES-256-CBC as encryption algorithm -func (o *OpenSSL) EncryptString(passphrase, plaintextString string) ([]byte, error) { +// functions using AES-256-CBC as encryption algorithm. Generating salt. +func (o *OpenSSL) EncryptString(passphrase string, plaintextString string) ([]byte, error) { salt := make([]byte, 8) // Generate an 8 byte salt _, err := io.ReadFull(rand.Reader, salt) if err != nil { return nil, err } + return o.EncryptStringWithSalt(passphrase, salt, plaintextString) +} + +// EncryptString encrypts a string in a manner compatible to OpenSSL encryption +// functions using AES-256-CBC as encryption algorithm. Ability to pass custom +// salt. +func (o *OpenSSL) EncryptStringWithSalt(passphrase string, salt []byte, plaintextString string) ([]byte, error) { data := make([]byte, len(plaintextString)+aes.BlockSize) copy(data[0:], o.openSSLSaltHeader) copy(data[8:], salt) diff --git a/openssl_test.go b/openssl_test.go index eca1acc..7044640 100644 --- a/openssl_test.go +++ b/openssl_test.go @@ -48,6 +48,50 @@ func TestEncryptToDecrypt(t *testing.T) { } } +func TestEncryptToDecryptWithCustomSalt(t *testing.T) { + plaintext := "hallowelt" + passphrase := "z4yH36a6zerhfE5427ZV" + salt := []byte("saltsalt") + + o := New() + + enc, err := o.EncryptStringWithSalt(passphrase, salt, plaintext) + if err != nil { + t.Fatalf("Test errored at encrypt: %s", err) + } + + dec, err := o.DecryptString(passphrase, string(enc)) + if err != nil { + t.Fatalf("Test errored at decrypt: %s", err) + } + + if string(dec) != plaintext { + t.Errorf("Decrypted text did not match input.") + } +} + +func TestEncryptWithSaltShouldHaveSameOutput(t *testing.T) { + plaintext := "outputshouldbesame" + passphrase := "passphrasesupersecure" + salt := []byte("saltsalt") + + o := New() + + enc1, err := o.EncryptStringWithSalt(passphrase, salt, plaintext) + if err != nil { + t.Fatalf("Test errored at encrypt: %s", err) + } + + enc2, err := o.EncryptStringWithSalt(passphrase, salt, plaintext) + if err != nil { + t.Fatalf("Test errored at encrypt: %s", err) + } + + if string(enc1) != string(enc2) { + t.Errorf("Encrypted outputs are not same.") + } +} + func TestEncryptToOpenSSL(t *testing.T) { plaintext := "hallowelt" passphrase := "z4yH36a6zerhfE5427ZV"