Skip to content

Add binding for EVP_BytesToKey() key derivation function #74

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions key.go
Original file line number Diff line number Diff line change
Expand Up @@ -420,3 +420,36 @@ func GenerateRSAKeyWithExponent(bits int, exponent int) (PrivateKey, error) {
})
return p, nil
}

// DeriveKey generates a key and IV from given password and salt using openssl EVP_BytesToKey()
func DeriveKey(cipher *Cipher, digest *Digest, salt []byte, password []byte,
iterations int) (key, iv []byte, err error) {

if len(salt)!=0 && len(salt)!=8 {
return nil, nil, errors.New("salt size must be 0 or 8 bytes")
}
if iterations < 1 {
return nil, nil, errors.New("iterations count must be 1 or greater")
}

key = make([]byte, cipher.KeySize())
iv = make([]byte, cipher.IVSize())

var saltPtr, ivPtr, passwordPtr, keyPtr *C.uchar
if len(salt) != 0 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so reading some openssl docs (https://wiki.openssl.org/index.php/Manual:EVP_BytesToKey(3)) this field should be either 8 bytes or null. can we have the function return an error if salt is passed and not 8 bytes?

saltPtr = (*C.uchar)(unsafe.Pointer(&salt[0]))
}
if len(iv) != 0 {
ivPtr = (*C.uchar)(unsafe.Pointer(&iv[0]))
}
passwordPtr = (*C.uchar)(unsafe.Pointer(&password[0]))
keyPtr = (*C.uchar)(unsafe.Pointer(&key[0]))

derivedKeySize := C.EVP_BytesToKey(cipher.ptr, digest.ptr, saltPtr,
passwordPtr, C.int(len(password)), C.int(iterations), keyPtr, ivPtr)
if derivedKeySize != C.int(cipher.KeySize()) {
return nil, nil, errors.New("key derivation failed")
}

return key, iv, nil
}