propogate errors

This commit is contained in:
Zack Scholl 2019-04-27 17:03:05 -07:00
parent f238c4b22c
commit 8dc8783bd4
2 changed files with 22 additions and 8 deletions

View File

@ -36,22 +36,35 @@ func (e encryption) Salt() []byte {
}
// Encrypt will generate an encryption, prefixed with the IV
func (e encryption) Encrypt(plaintext []byte) []byte {
func (e encryption) Encrypt(plaintext []byte) (encrypted []byte, err error) {
// generate a random iv each time
// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
// Section 8.2
ivBytes := make([]byte, 12)
rand.Read(ivBytes)
b, _ := aes.NewCipher(e.key)
aesgcm, _ := cipher.NewGCM(b)
encrypted := aesgcm.Seal(nil, ivBytes, plaintext, nil)
return append(ivBytes, encrypted...)
b, err := aes.NewCipher(e.key)
if err != nil {
return
}
aesgcm, err := cipher.NewGCM(b)
if err != nil {
return
}
encrypted = aesgcm.Seal(nil, ivBytes, plaintext, nil)
encrypted = append(ivBytes, encrypted...)
return
}
// Decrypt an encryption
func (e encryption) Decrypt(encrypted []byte) (plaintext []byte, err error) {
b, _ := aes.NewCipher(e.key)
aesgcm, _ := cipher.NewGCM(b)
b, err := aes.NewCipher(e.key)
if err != nil {
return
}
aesgcm, err := cipher.NewGCM(b)
if err != nil {
return
}
plaintext, err = aesgcm.Open(nil, encrypted[:12], encrypted[12:], nil)
return
}

View File

@ -25,7 +25,8 @@ func TestEncryption(t *testing.T) {
assert.Nil(t, err)
jane, err := New([]byte("password"), bob.Salt())
assert.Nil(t, err)
enc := bob.Encrypt([]byte("hello, world"))
enc, err := bob.Encrypt([]byte("hello, world"))
assert.Nil(t, err)
dec, err := jane.Decrypt(enc)
assert.Nil(t, err)
assert.Equal(t, dec, []byte("hello, world"))