/
keycrypt.go
executable file
·174 lines (141 loc) · 4.07 KB
/
keycrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package keycrypt
import (
"bytes"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
"unicode/utf16"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/muun/libwallet/aescbc"
"golang.org/x/crypto/scrypt"
)
const (
ivLength = 16
saltLength = 8
scryptIterations = 512
scryptBlockSize = 8
scryptParallelizationFactor = 1
scryptOutputLength = 32
separator = ":"
)
// Encrypt 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.
func Encrypt(key *hdkeychain.ExtendedKey, keyPath, passphrase string) (string, error) {
iv := randomBytes(ivLength)
salt := randomBytes(saltLength)
inputSecret, err := scrypt.Key(
encodeUTF16(passphrase),
salt,
scryptIterations,
scryptBlockSize,
scryptParallelizationFactor,
scryptOutputLength,
)
if err != nil {
return "", fmt.Errorf("failed to compute scrypt key: %w", err)
}
privateKeyBytes := []byte(key.String())
encrypted, err := aescbc.EncryptPkcs7(inputSecret, iv, privateKeyBytes)
if err != nil {
return "", fmt.Errorf("failed to encrypt: %w", err)
}
derivationPathBytes := []byte(keyPath)
elements := []string{
"v1",
strconv.Itoa(scryptIterations),
strconv.Itoa(scryptParallelizationFactor),
strconv.Itoa(scryptBlockSize),
hex.EncodeToString(salt),
hex.EncodeToString(iv),
hex.EncodeToString(encrypted),
hex.EncodeToString(derivationPathBytes),
}
return strings.Join(elements, separator), nil
}
// Decrypt decrypts a key encrypted with Encrypt
func Decrypt(value, passphrase string) (*hdkeychain.ExtendedKey, string, error) {
elements := strings.Split(value, separator)
if len(elements) != 8 {
return nil, "", errors.New("invalid format")
}
version := elements[0]
iterations, err := strconv.Atoi(elements[1])
if err != nil {
return nil, "", fmt.Errorf("invalid iterations: %w", err)
}
parallelizationFactor, err := strconv.Atoi(elements[2])
if err != nil {
return nil, "", fmt.Errorf("invalid p: %w", err)
}
blockSize, err := strconv.Atoi(elements[3])
if err != nil {
return nil, "", fmt.Errorf("invalid blocksize: %w", err)
}
salt, err := hex.DecodeString(elements[4])
if err != nil {
return nil, "", fmt.Errorf("invalid salt: %w", err)
}
iv, err := hex.DecodeString(elements[5])
if err != nil {
return nil, "", fmt.Errorf("invalid iv: %w", err)
}
payload, err := hex.DecodeString(elements[6])
if err != nil {
return nil, "", fmt.Errorf("invalid payload: %w", err)
}
pathBytes, err := hex.DecodeString(elements[7])
if err != nil {
return nil, "", fmt.Errorf("invalid path: %w", err)
}
if version != "v1" {
return nil, "", fmt.Errorf("invalid version %s", version)
}
inputSecret, err := scrypt.Key(
encodeUTF16(passphrase),
salt,
iterations,
blockSize,
parallelizationFactor,
scryptOutputLength,
)
if err != nil {
return nil, "", fmt.Errorf("failed to compute scrypt key: %w", err)
}
decryptedBytes, err := aescbc.DecryptPkcs7(inputSecret, iv, payload)
if err != nil {
return nil, "", fmt.Errorf("failed to decrypt: %w", err)
}
key, err := hdkeychain.NewKeyFromString(string(decryptedBytes[:]))
if err != nil {
return nil, "", fmt.Errorf("could not decode private key: %w", err)
}
if !key.IsPrivate() {
return nil, "", errors.New("expected extended key to be private, not public")
}
path := string(pathBytes[:])
return key, path, nil
}
func randomBytes(count int) []byte {
buf := make([]byte, count)
_, err := rand.Read(buf)
if err != nil {
panic("couldn't read random bytes")
}
return buf
}
func encodeUTF16(s string) []byte {
// You might wonder why this code exists....
// Turns out that the scrypt implementation used in android is hardwired
// to use strings as UTF16 (which is Java's native format). So we need to
// use the same exact byte array encoding.
var buf bytes.Buffer
for _, r := range utf16.Encode([]rune(s)) {
binary.Write(&buf, binary.BigEndian, r)
}
return buf.Bytes()
}