0
0
Fork 0
mirror of https://github.com/schollz/croc.git synced 2025-10-11 13:21:00 +02:00

modify api of salt

This commit is contained in:
Zack Scholl 2019-04-27 16:49:00 -07:00
parent 249c0d8ab0
commit f238c4b22c
2 changed files with 14 additions and 11 deletions

View file

@ -9,31 +9,34 @@ import (
"golang.org/x/crypto/pbkdf2" "golang.org/x/crypto/pbkdf2"
) )
// Encryption stores the data type encryption struct {
type Encryption struct {
key []byte key []byte
passphrase []byte passphrase []byte
Salt []byte `json:"s"` salt []byte
} }
// New generates a new encryption, using the supplied passphrase and // New generates a new encryption, using the supplied passphrase and
// an optional supplied salt. // an optional supplied salt.
func New(passphrase []byte, salt []byte) (e Encryption, err error) { func New(passphrase []byte, salt []byte) (e encryption, err error) {
e.passphrase = passphrase e.passphrase = passphrase
if salt == nil { if salt == nil {
e.Salt = make([]byte, 8) e.salt = make([]byte, 8)
// http://www.ietf.org/rfc/rfc2898.txt // http://www.ietf.org/rfc/rfc2898.txt
// Salt. // Salt.
rand.Read(e.Salt) rand.Read(e.salt)
} else { } else {
e.Salt = salt e.salt = salt
} }
e.key = pbkdf2.Key([]byte(passphrase), e.Salt, 100, 32, sha256.New) e.key = pbkdf2.Key([]byte(passphrase), e.salt, 100, 32, sha256.New)
return return
} }
func (e encryption) Salt() []byte {
return e.salt
}
// Encrypt will generate an encryption, prefixed with the IV // Encrypt will generate an encryption, prefixed with the IV
func (e Encryption) Encrypt(plaintext []byte) []byte { func (e encryption) Encrypt(plaintext []byte) []byte {
// generate a random iv each time // generate a random iv each time
// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf // http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
// Section 8.2 // Section 8.2
@ -46,7 +49,7 @@ func (e Encryption) Encrypt(plaintext []byte) []byte {
} }
// Decrypt an encryption // Decrypt an encryption
func (e Encryption) Decrypt(encrypted []byte) (plaintext []byte, err error) { func (e encryption) Decrypt(encrypted []byte) (plaintext []byte, err error) {
b, _ := aes.NewCipher(e.key) b, _ := aes.NewCipher(e.key)
aesgcm, _ := cipher.NewGCM(b) aesgcm, _ := cipher.NewGCM(b)
plaintext, err = aesgcm.Open(nil, encrypted[:12], encrypted[12:], nil) plaintext, err = aesgcm.Open(nil, encrypted[:12], encrypted[12:], nil)

View file

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