2018-06-01 15:34:46 +00:00
|
|
|
package openssl
|
2017-03-21 13:55:49 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
|
|
|
"crypto/md5"
|
|
|
|
"crypto/rand"
|
2018-09-14 11:18:07 +00:00
|
|
|
"crypto/sha1"
|
|
|
|
"crypto/sha256"
|
2017-03-21 13:55:49 +00:00
|
|
|
"encoding/base64"
|
2018-06-01 15:34:46 +00:00
|
|
|
"errors"
|
2017-03-21 13:55:49 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
// CurrentOpenSSLDigestFunc is an alias to the key derivation function used in OpenSSL
|
|
|
|
var CurrentOpenSSLDigestFunc = DigestSHA256Sum
|
|
|
|
|
|
|
|
// ErrInvalidSalt is returned when a salt with a length of != 8 byte is passed
|
2018-06-01 15:34:46 +00:00
|
|
|
var ErrInvalidSalt = errors.New("Salt needs to have exactly 8 byte")
|
|
|
|
|
2017-03-21 13:55:49 +00:00
|
|
|
// OpenSSL is a helper to generate OpenSSL compatible encryption
|
|
|
|
// with autmatic IV derivation and storage. As long as the key is known all
|
|
|
|
// data can also get decrypted using OpenSSL CLI.
|
|
|
|
// Code from http://dequeue.blogspot.de/2014/11/decrypting-something-encrypted-with.html
|
|
|
|
type OpenSSL struct {
|
|
|
|
openSSLSaltHeader string
|
|
|
|
}
|
|
|
|
|
|
|
|
type openSSLCreds struct {
|
|
|
|
key []byte
|
|
|
|
iv []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
// New instanciates and initializes a new OpenSSL encrypter
|
|
|
|
func New() *OpenSSL {
|
|
|
|
return &OpenSSL{
|
|
|
|
openSSLSaltHeader: "Salted__", // OpenSSL salt is always this string + 8 bytes of actual salt
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
// DigestFunc are functions to create a key from the passphrase
|
|
|
|
type DigestFunc func([]byte) []byte
|
|
|
|
|
|
|
|
// DigestMD5Sum uses the (deprecated) pre-OpenSSL 1.1.0c MD5 digest to create the key
|
|
|
|
func DigestMD5Sum(data []byte) []byte {
|
|
|
|
h := md5.New()
|
|
|
|
h.Write(data)
|
|
|
|
return h.Sum(nil)
|
2018-06-01 15:34:46 +00:00
|
|
|
}
|
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
// DigestSHA1Sum uses SHA1 digest to create the key
|
|
|
|
func DigestSHA1Sum(data []byte) []byte {
|
|
|
|
h := sha1.New()
|
|
|
|
h.Write(data)
|
|
|
|
return h.Sum(nil)
|
|
|
|
}
|
2018-09-14 11:18:07 +00:00
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
// DigestSHA256Sum uses SHA256 digest to create the key which is the default behaviour since OpenSSL 1.1.0c
|
|
|
|
func DigestSHA256Sum(data []byte) []byte {
|
|
|
|
h := sha256.New()
|
|
|
|
h.Write(data)
|
|
|
|
return h.Sum(nil)
|
2018-09-14 11:18:07 +00:00
|
|
|
}
|
|
|
|
|
2018-06-01 15:34:46 +00:00
|
|
|
// DecryptBytes takes a slice of bytes with base64 encoded, encrypted data to decrypt
|
2018-11-02 20:41:30 +00:00
|
|
|
// and a key-derivation function. The key-derivation function must match the function
|
|
|
|
// used to encrypt the data. (In OpenSSL the value of the `-md` parameter.)
|
|
|
|
//
|
|
|
|
// You should not just try to loop the digest functions as this will cause a race
|
|
|
|
// condition and you will not be able to decrypt your data properly.
|
|
|
|
func (o OpenSSL) DecryptBytes(passphrase string, encryptedBase64Data []byte, kdf DigestFunc) ([]byte, error) {
|
2018-06-01 15:34:46 +00:00
|
|
|
data := make([]byte, base64.StdEncoding.DecodedLen(len(encryptedBase64Data)))
|
|
|
|
n, err := base64.StdEncoding.Decode(data, encryptedBase64Data)
|
2017-03-21 13:55:49 +00:00
|
|
|
if err != nil {
|
2018-06-01 15:34:46 +00:00
|
|
|
return nil, fmt.Errorf("Could not decode data: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Truncate to real message length
|
|
|
|
data = data[0:n]
|
|
|
|
|
|
|
|
if len(data) < aes.BlockSize {
|
|
|
|
return nil, fmt.Errorf("Data is too short")
|
2017-03-21 13:55:49 +00:00
|
|
|
}
|
|
|
|
saltHeader := data[:aes.BlockSize]
|
|
|
|
if string(saltHeader[:8]) != o.openSSLSaltHeader {
|
2018-11-02 20:41:30 +00:00
|
|
|
return nil, fmt.Errorf("Does not appear to have been encrypted with OpenSSL, salt header missing")
|
2017-03-21 13:55:49 +00:00
|
|
|
}
|
|
|
|
salt := saltHeader[8:]
|
2018-09-14 11:18:07 +00:00
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
creds, err := o.extractOpenSSLCreds([]byte(passphrase), salt, kdf)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2017-03-21 13:55:49 +00:00
|
|
|
}
|
2018-11-02 20:41:30 +00:00
|
|
|
return o.decrypt(creds.key, creds.iv, data)
|
2017-03-21 13:55:49 +00:00
|
|
|
}
|
|
|
|
|
2018-06-01 15:34:46 +00:00
|
|
|
func (o OpenSSL) decrypt(key, iv, data []byte) ([]byte, error) {
|
2017-03-21 13:55:49 +00:00
|
|
|
if len(data) == 0 || len(data)%aes.BlockSize != 0 {
|
2018-11-02 20:41:30 +00:00
|
|
|
return nil, fmt.Errorf("bad blocksize(%v), aes.BlockSize = %v", len(data), aes.BlockSize)
|
2017-03-21 13:55:49 +00:00
|
|
|
}
|
|
|
|
c, err := aes.NewCipher(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
cbc := cipher.NewCBCDecrypter(c, iv)
|
|
|
|
cbc.CryptBlocks(data[aes.BlockSize:], data[aes.BlockSize:])
|
|
|
|
out, err := o.pkcs7Unpad(data[aes.BlockSize:], aes.BlockSize)
|
|
|
|
if out == nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return out, nil
|
|
|
|
}
|
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
// EncryptBytes encrypts a slice of bytes in a manner compatible to OpenSSL encryption
|
2018-06-01 15:34:46 +00:00
|
|
|
// functions using AES-256-CBC as encryption algorithm. This function generates
|
|
|
|
// a random salt on every execution.
|
2018-11-02 20:41:30 +00:00
|
|
|
func (o OpenSSL) EncryptBytes(passphrase string, plainData []byte, kdf DigestFunc) ([]byte, error) {
|
2018-09-14 11:18:07 +00:00
|
|
|
salt, err := o.GenerateSalt()
|
2017-03-21 13:55:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
return o.EncryptBytesWithSaltAndDigestFunc(passphrase, salt, plainData, kdf)
|
2018-09-14 11:18:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// EncryptBytesWithSaltAndDigestFunc encrypts a slice of bytes in a manner compatible to OpenSSL
|
|
|
|
// encryption functions using AES-256-CBC as encryption algorithm. The salt
|
|
|
|
// needs to be passed in here which ensures the same result on every execution
|
|
|
|
// on cost of a much weaker encryption as with EncryptString.
|
|
|
|
//
|
|
|
|
// The salt passed into this function needs to have exactly 8 byte.
|
|
|
|
//
|
|
|
|
// The hash function corresponds to the `-md` parameter of OpenSSL. For OpenSSL pre-1.1.0c
|
|
|
|
// DigestMD5Sum was the default, since then it is DigestSHA256Sum.
|
|
|
|
//
|
|
|
|
// If you don't have a good reason to use this, please don't! For more information
|
|
|
|
// see this: https://en.wikipedia.org/wiki/Salt_(cryptography)#Common_mistakes
|
|
|
|
func (o OpenSSL) EncryptBytesWithSaltAndDigestFunc(passphrase string, salt, plainData []byte, hashFunc DigestFunc) ([]byte, error) {
|
2018-06-01 15:34:46 +00:00
|
|
|
if len(salt) != 8 {
|
|
|
|
return nil, ErrInvalidSalt
|
|
|
|
}
|
|
|
|
|
|
|
|
data := make([]byte, len(plainData)+aes.BlockSize)
|
2017-03-21 13:55:49 +00:00
|
|
|
copy(data[0:], o.openSSLSaltHeader)
|
|
|
|
copy(data[8:], salt)
|
2018-06-01 15:34:46 +00:00
|
|
|
copy(data[aes.BlockSize:], plainData)
|
2017-03-21 13:55:49 +00:00
|
|
|
|
2018-09-14 11:18:07 +00:00
|
|
|
creds, err := o.extractOpenSSLCreds([]byte(passphrase), salt, hashFunc)
|
2017-03-21 13:55:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
enc, err := o.encrypt(creds.key, creds.iv, data)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return []byte(base64.StdEncoding.EncodeToString(enc)), nil
|
|
|
|
}
|
|
|
|
|
2018-06-01 15:34:46 +00:00
|
|
|
func (o OpenSSL) encrypt(key, iv, data []byte) ([]byte, error) {
|
2017-03-21 13:55:49 +00:00
|
|
|
padded, err := o.pkcs7Pad(data, aes.BlockSize)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
c, err := aes.NewCipher(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
cbc := cipher.NewCBCEncrypter(c, iv)
|
|
|
|
cbc.CryptBlocks(padded[aes.BlockSize:], padded[aes.BlockSize:])
|
|
|
|
|
|
|
|
return padded, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// openSSLEvpBytesToKey follows the OpenSSL (undocumented?) convention for extracting the key and IV from passphrase.
|
|
|
|
// It uses the EVP_BytesToKey() method which is basically:
|
|
|
|
// D_i = HASH^count(D_(i-1) || password || salt) where || denotes concatentaion, until there are sufficient bytes available
|
|
|
|
// 48 bytes since we're expecting to handle AES-256, 32bytes for a key and 16bytes for the IV
|
2018-09-14 11:18:07 +00:00
|
|
|
func (o OpenSSL) extractOpenSSLCreds(password, salt []byte, hashFunc DigestFunc) (openSSLCreds, error) {
|
|
|
|
var m []byte
|
2017-03-21 13:55:49 +00:00
|
|
|
prev := []byte{}
|
2018-09-14 11:18:07 +00:00
|
|
|
for len(m) < 48 {
|
|
|
|
prev = o.hash(prev, password, salt, hashFunc)
|
|
|
|
m = append(m, prev...)
|
2017-03-21 13:55:49 +00:00
|
|
|
}
|
2018-09-14 11:18:07 +00:00
|
|
|
return openSSLCreds{key: m[:32], iv: m[32:48]}, nil
|
2017-03-21 13:55:49 +00:00
|
|
|
}
|
|
|
|
|
2018-09-14 11:18:07 +00:00
|
|
|
func (o OpenSSL) hash(prev, password, salt []byte, hashFunc DigestFunc) []byte {
|
2017-03-21 13:55:49 +00:00
|
|
|
a := make([]byte, len(prev)+len(password)+len(salt))
|
|
|
|
copy(a, prev)
|
|
|
|
copy(a[len(prev):], password)
|
|
|
|
copy(a[len(prev)+len(password):], salt)
|
2018-09-14 11:18:07 +00:00
|
|
|
return hashFunc(a)
|
2017-03-21 13:55:49 +00:00
|
|
|
}
|
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
// GenerateSalt generates a random 8 byte salt
|
|
|
|
func (o OpenSSL) GenerateSalt() ([]byte, error) {
|
|
|
|
salt := make([]byte, 8) // Generate an 8 byte salt
|
|
|
|
_, err := io.ReadFull(rand.Reader, salt)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-09-14 11:18:07 +00:00
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
return salt, nil
|
2018-09-14 11:18:07 +00:00
|
|
|
}
|
|
|
|
|
2018-11-02 20:41:30 +00:00
|
|
|
// MustGenerateSalt is a wrapper around GenerateSalt which will panic on an error.
|
|
|
|
// This allows you to use this function as a parameter to EncryptBytesWithSaltAndDigestFunc
|
|
|
|
func (o OpenSSL) MustGenerateSalt() []byte {
|
|
|
|
s, err := o.GenerateSalt()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return s
|
2017-03-21 13:55:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// pkcs7Pad appends padding.
|
2018-06-01 15:34:46 +00:00
|
|
|
func (o OpenSSL) pkcs7Pad(data []byte, blocklen int) ([]byte, error) {
|
2017-03-21 13:55:49 +00:00
|
|
|
if blocklen <= 0 {
|
|
|
|
return nil, fmt.Errorf("invalid blocklen %d", blocklen)
|
|
|
|
}
|
|
|
|
padlen := 1
|
|
|
|
for ((len(data) + padlen) % blocklen) != 0 {
|
|
|
|
padlen = padlen + 1
|
|
|
|
}
|
|
|
|
|
|
|
|
pad := bytes.Repeat([]byte{byte(padlen)}, padlen)
|
|
|
|
return append(data, pad...), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// pkcs7Unpad returns slice of the original data without padding.
|
2018-06-01 15:34:46 +00:00
|
|
|
func (o OpenSSL) pkcs7Unpad(data []byte, blocklen int) ([]byte, error) {
|
2017-03-21 13:55:49 +00:00
|
|
|
if blocklen <= 0 {
|
|
|
|
return nil, fmt.Errorf("invalid blocklen %d", blocklen)
|
|
|
|
}
|
|
|
|
if len(data)%blocklen != 0 || len(data) == 0 {
|
|
|
|
return nil, fmt.Errorf("invalid data len %d", len(data))
|
|
|
|
}
|
|
|
|
padlen := int(data[len(data)-1])
|
|
|
|
if padlen > blocklen || padlen == 0 {
|
|
|
|
return nil, fmt.Errorf("invalid padding")
|
|
|
|
}
|
|
|
|
pad := data[len(data)-padlen:]
|
|
|
|
for i := 0; i < padlen; i++ {
|
|
|
|
if pad[i] != byte(padlen) {
|
|
|
|
return nil, fmt.Errorf("invalid padding")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return data[:len(data)-padlen], nil
|
|
|
|
}
|