2019-10-01 12:22:30 -03:00
|
|
|
package libwallet
|
|
|
|
|
|
|
|
import (
|
2020-11-09 10:05:29 -03:00
|
|
|
"fmt"
|
2019-10-01 12:22:30 -03:00
|
|
|
|
2020-11-09 10:05:29 -03:00
|
|
|
"github.com/muun/libwallet/keycrypt"
|
2019-10-01 12:22:30 -03:00
|
|
|
)
|
|
|
|
|
|
|
|
type DecryptedKey struct {
|
|
|
|
Key *HDPrivateKey
|
|
|
|
Path string
|
|
|
|
}
|
|
|
|
|
|
|
|
// KeyEncrypt encrypts an HD priv key using a user-provided secret into a string
|
|
|
|
// We use SCrypt256 for key derivation and AES-CBC-PKCS7 for encryption.
|
|
|
|
// The returned string has information about version, derivation path, scrypt and AES parameters.
|
2020-11-09 10:05:29 -03:00
|
|
|
func KeyEncrypt(privKey *HDPrivateKey, passphrase string) (string, error) {
|
|
|
|
ciphertext, err := keycrypt.Encrypt(&privKey.key, privKey.Path, passphrase)
|
2019-10-01 12:22:30 -03:00
|
|
|
if err != nil {
|
2020-11-09 10:05:29 -03:00
|
|
|
return "", fmt.Errorf("KeyEncrypt: failed to encrypt: %w", err)
|
2019-10-01 12:22:30 -03:00
|
|
|
}
|
2020-11-09 10:05:29 -03:00
|
|
|
return ciphertext, nil
|
2019-10-01 12:22:30 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
// KeyDecrypt decrypts a key encrypted with KeyEncrypt
|
2019-12-16 17:59:11 -03:00
|
|
|
func KeyDecrypt(value, passphrase string, network *Network) (*DecryptedKey, error) {
|
2020-11-09 10:05:29 -03:00
|
|
|
key, path, err := keycrypt.Decrypt(value, passphrase)
|
2019-10-01 12:22:30 -03:00
|
|
|
if err != nil {
|
2020-11-09 10:05:29 -03:00
|
|
|
return nil, fmt.Errorf("KeyDecrypt: failed to decrypt: %w", err)
|
2019-10-01 12:22:30 -03:00
|
|
|
}
|
2020-11-09 10:05:29 -03:00
|
|
|
privateKey := &HDPrivateKey{key: *key, Network: network, Path: path}
|
2019-10-01 12:22:30 -03:00
|
|
|
|
|
|
|
return &DecryptedKey{Key: privateKey, Path: path}, nil
|
|
|
|
}
|