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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#![cfg_attr(docsrs, feature(doc_cfg))]
use ctr::cipher::{NewCipher, StreamCipher};
use digest::Digest;
use hmac::Hmac;
use pbkdf2::pbkdf2;
use scrypt::{scrypt, Params as ScryptParams};
use sha2::Sha256;
use sha3::Keccak256;
use rand::{CryptoRng, Rng};
use std::{
fs::File,
io::{Read, Write},
path::Path,
};
use uuid::Uuid;
mod error;
mod keystore;
pub use error::KeystoreError;
pub use keystore::{CipherparamsJson, CryptoJson, EthKeystore, KdfType, KdfparamsType};
type Aes128Ctr = ctr::Ctr128BE<aes::Aes128>;
const DEFAULT_CIPHER: &str = "aes-128-ctr";
const DEFAULT_KEY_SIZE: usize = 32usize;
const DEFAULT_IV_SIZE: usize = 16usize;
const DEFAULT_KDF_PARAMS_DKLEN: u8 = 32u8;
const DEFAULT_KDF_PARAMS_LOG_N: u8 = 13u8;
const DEFAULT_KDF_PARAMS_R: u32 = 8u32;
const DEFAULT_KDF_PARAMS_P: u32 = 1u32;
pub fn new<P, R, S>(dir: P, rng: &mut R, password: S) -> Result<(Vec<u8>, String), KeystoreError>
where
P: AsRef<Path>,
R: Rng + CryptoRng,
S: AsRef<[u8]>,
{
let mut pk = vec![0u8; DEFAULT_KEY_SIZE];
rng.fill_bytes(pk.as_mut_slice());
let uuid = encrypt_key(dir, rng, pk.clone(), password)?;
Ok((pk, uuid))
}
pub fn decrypt_key<P, S>(path: P, password: S) -> Result<Vec<u8>, KeystoreError>
where
P: AsRef<Path>,
S: AsRef<[u8]>,
{
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let keystore: EthKeystore = serde_json::from_str(&contents)?;
let key = match keystore.crypto.kdfparams {
KdfparamsType::Pbkdf2 {
c,
dklen,
prf: _,
salt,
} => {
let mut key = vec![0u8; dklen as usize];
pbkdf2::<Hmac<Sha256>>(password.as_ref(), &salt, c, key.as_mut_slice());
key
}
KdfparamsType::Scrypt {
dklen,
n,
p,
r,
salt,
} => {
let mut key = vec![0u8; dklen as usize];
let log_n = (n as f32).log2() as u8;
let scrypt_params = ScryptParams::new(log_n, r, p)?;
scrypt(password.as_ref(), &salt, &scrypt_params, key.as_mut_slice())?;
key
}
};
let derived_mac = Keccak256::new()
.chain(&key[16..32])
.chain(&keystore.crypto.ciphertext)
.finalize();
if derived_mac.as_slice() != keystore.crypto.mac.as_slice() {
return Err(KeystoreError::MacMismatch);
}
let mut decryptor = Aes128Ctr::new(
(&key[..16]).into(),
(&keystore.crypto.cipherparams.iv[..16]).into(),
);
let mut pk = keystore.crypto.ciphertext.clone();
decryptor.apply_keystream(&mut pk);
Ok(pk)
}
pub fn encrypt_key<P, R, B, S>(
dir: P,
rng: &mut R,
pk: B,
password: S,
) -> Result<String, KeystoreError>
where
P: AsRef<Path>,
R: Rng + CryptoRng,
B: AsRef<[u8]>,
S: AsRef<[u8]>,
{
let mut salt = vec![0u8; DEFAULT_KEY_SIZE];
rng.fill_bytes(salt.as_mut_slice());
let mut key = vec![0u8; DEFAULT_KDF_PARAMS_DKLEN as usize];
let scrypt_params = ScryptParams::new(
DEFAULT_KDF_PARAMS_LOG_N,
DEFAULT_KDF_PARAMS_R,
DEFAULT_KDF_PARAMS_P,
)?;
scrypt(password.as_ref(), &salt, &scrypt_params, key.as_mut_slice())?;
let mut iv = vec![0u8; DEFAULT_IV_SIZE];
rng.fill_bytes(iv.as_mut_slice());
let mut encryptor = Aes128Ctr::new((&key[..16]).into(), (&iv[..16]).into());
let mut ciphertext = pk.as_ref().to_vec();
encryptor.apply_keystream(&mut ciphertext);
let mac = Keccak256::new()
.chain(&key[16..32])
.chain(&ciphertext)
.finalize();
let id = Uuid::new_v4();
let keystore = EthKeystore {
id,
version: 3,
crypto: CryptoJson {
cipher: String::from(DEFAULT_CIPHER),
cipherparams: CipherparamsJson { iv },
ciphertext: ciphertext.to_vec(),
kdf: KdfType::Scrypt,
kdfparams: KdfparamsType::Scrypt {
dklen: DEFAULT_KDF_PARAMS_DKLEN,
n: 2u32.pow(DEFAULT_KDF_PARAMS_LOG_N as u32),
p: DEFAULT_KDF_PARAMS_P,
r: DEFAULT_KDF_PARAMS_R,
salt,
},
mac: mac.to_vec(),
},
};
let contents = serde_json::to_string(&keystore)?;
let mut file = File::create(dir.as_ref().join(id.to_string()))?;
file.write_all(contents.as_bytes())?;
Ok(id.to_string())
}