forked from tronprotocol/java-tron
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWallet.java
More file actions
238 lines (190 loc) · 8.76 KB
/
Wallet.java
File metadata and controls
238 lines (190 loc) · 8.76 KB
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
233
234
235
236
237
238
package org.tron.keystore;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.UUID;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.generators.SCrypt;
import org.bouncycastle.crypto.params.KeyParameter;
import org.tron.common.crypto.Hash;
import org.tron.common.crypto.SignInterface;
import org.tron.common.crypto.SignUtils;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.StringUtil;
import org.tron.core.exception.CipherException;
/**
* <p>Ethereum wallet file management. For reference, refer to <a href="https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition">
* Web3 Secret Storage Definition</a> or the <a href="https://github.com/ethereum/go-ethereum/blob/master/accounts/key_store_passphrase.go">
* Go Ethereum client implementation</a>.</p>
*
* <p><strong>Note:</strong> the Bouncy Castle Scrypt implementation {@link SCrypt}, fails to
* comply
* with the following Ethereum reference <a href="https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition#scrypt">
* Scrypt test vector</a>:</p>
*
* <pre>
* {@code
* // Only value of r that cost (as an int) could be exceeded for is 1
* if (r == 1 && N_STANDARD > 65536)
* {
* throw new IllegalArgumentException("Cost parameter N_STANDARD must be > 1 and < 65536.");
* }
* }
* </pre>
*/
public class Wallet {
protected static final String AES_128_CTR = "pbkdf2";
protected static final String SCRYPT = "scrypt";
private static final int N_LIGHT = 1 << 12;
private static final int P_LIGHT = 6;
private static final int N_STANDARD = 1 << 18;
private static final int P_STANDARD = 1;
private static final int R = 8;
private static final int DKLEN = 32;
private static final int CURRENT_VERSION = 3;
private static final String CIPHER = "aes-128-ctr";
public static WalletFile create(String password, SignInterface sign, int n, int p)
throws CipherException {
byte[] salt = generateRandomBytes(32);
byte[] derivedKey = generateDerivedScryptKey(password.getBytes(UTF_8), salt, n, R, p, DKLEN);
byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16);
byte[] iv = generateRandomBytes(16);
byte[] privateKeyBytes = sign.getPrivateKey();
byte[] cipherText = performCipherOperation(Cipher.ENCRYPT_MODE, iv, encryptKey,
privateKeyBytes);
byte[] mac = generateMac(derivedKey, cipherText);
return createWalletFile(sign, cipherText, iv, salt, mac, n, p);
}
public static WalletFile createStandard(String password, SignInterface cryptoEngine)
throws CipherException {
return create(password, cryptoEngine, N_STANDARD, P_STANDARD);
}
public static WalletFile createLight(String password, SignInterface cryptoEngine)
throws CipherException {
return create(password, cryptoEngine, N_LIGHT, P_LIGHT);
}
private static WalletFile createWalletFile(
SignInterface ecKeyPair, byte[] cipherText, byte[] iv, byte[] salt, byte[] mac,
int n, int p) {
WalletFile walletFile = new WalletFile();
walletFile.setAddress(StringUtil.encode58Check(ecKeyPair.getAddress()));
WalletFile.Crypto crypto = new WalletFile.Crypto();
crypto.setCipher(CIPHER);
crypto.setCiphertext(ByteArray.toHexString(cipherText));
walletFile.setCrypto(crypto);
WalletFile.CipherParams cipherParams = new WalletFile.CipherParams();
cipherParams.setIv(ByteArray.toHexString(iv));
crypto.setCipherparams(cipherParams);
crypto.setKdf(SCRYPT);
WalletFile.ScryptKdfParams kdfParams = new WalletFile.ScryptKdfParams();
kdfParams.setDklen(DKLEN);
kdfParams.setN(n);
kdfParams.setP(p);
kdfParams.setR(R);
kdfParams.setSalt(ByteArray.toHexString(salt));
crypto.setKdfparams(kdfParams);
crypto.setMac(ByteArray.toHexString(mac));
walletFile.setCrypto(crypto);
walletFile.setId(UUID.randomUUID().toString());
walletFile.setVersion(CURRENT_VERSION);
return walletFile;
}
private static byte[] generateDerivedScryptKey(
byte[] password, byte[] salt, int n, int r, int p, int dkLen) throws CipherException {
return SCrypt.generate(password, salt, n, r, p, dkLen);
}
private static byte[] generateAes128CtrDerivedKey(
byte[] password, byte[] salt, int c, String prf) throws CipherException {
if (!"hmac-sha256".equals(prf)) {
throw new CipherException("Unsupported prf:" + prf);
}
// Java 8 supports this, but you have to convert the password to a character array, see
// http://stackoverflow.com/a/27928435/3211687
PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
gen.init(password, salt, c);
return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
}
private static byte[] performCipherOperation(
int mode, byte[] iv, byte[] encryptKey, byte[] text) throws CipherException {
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES");
cipher.init(mode, secretKeySpec, ivParameterSpec);
return cipher.doFinal(text);
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidAlgorithmParameterException | InvalidKeyException
| BadPaddingException | IllegalBlockSizeException e) {
throw new CipherException("Error performing cipher operation", e);
}
}
private static byte[] generateMac(byte[] derivedKey, byte[] cipherText) {
byte[] result = new byte[16 + cipherText.length];
System.arraycopy(derivedKey, 16, result, 0, 16);
System.arraycopy(cipherText, 0, result, 16, cipherText.length);
return Hash.sha3(result);
}
public static SignInterface decrypt(String password, WalletFile walletFile,
boolean ecKey) throws CipherException {
validate(walletFile);
WalletFile.Crypto crypto = walletFile.getCrypto();
byte[] mac = ByteArray.fromHexString(crypto.getMac());
byte[] iv = ByteArray.fromHexString(crypto.getCipherparams().getIv());
byte[] cipherText = ByteArray.fromHexString(crypto.getCiphertext());
byte[] derivedKey;
WalletFile.KdfParams kdfParams = crypto.getKdfparams();
if (kdfParams instanceof WalletFile.ScryptKdfParams) {
WalletFile.ScryptKdfParams scryptKdfParams =
(WalletFile.ScryptKdfParams) crypto.getKdfparams();
int dklen = scryptKdfParams.getDklen();
int n = scryptKdfParams.getN();
int p = scryptKdfParams.getP();
int r = scryptKdfParams.getR();
byte[] salt = ByteArray.fromHexString(scryptKdfParams.getSalt());
derivedKey = generateDerivedScryptKey(password.getBytes(UTF_8), salt, n, r, p, dklen);
} else if (kdfParams instanceof WalletFile.Aes128CtrKdfParams) {
WalletFile.Aes128CtrKdfParams aes128CtrKdfParams =
(WalletFile.Aes128CtrKdfParams) crypto.getKdfparams();
int c = aes128CtrKdfParams.getC();
String prf = aes128CtrKdfParams.getPrf();
byte[] salt = ByteArray.fromHexString(aes128CtrKdfParams.getSalt());
derivedKey = generateAes128CtrDerivedKey(password.getBytes(UTF_8), salt, c, prf);
} else {
throw new CipherException("Unable to deserialize params: " + crypto.getKdf());
}
byte[] derivedMac = generateMac(derivedKey, cipherText);
if (!java.security.MessageDigest.isEqual(derivedMac, mac)) {
throw new CipherException("Invalid password provided");
}
byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16);
byte[] privateKey = performCipherOperation(Cipher.DECRYPT_MODE, iv, encryptKey, cipherText);
return SignUtils.fromPrivate(privateKey, ecKey);
}
static void validate(WalletFile walletFile) throws CipherException {
WalletFile.Crypto crypto = walletFile.getCrypto();
if (walletFile.getVersion() != CURRENT_VERSION) {
throw new CipherException("Wallet version is not supported");
}
if (!crypto.getCipher().equals(CIPHER)) {
throw new CipherException("Wallet cipher is not supported");
}
if (!crypto.getKdf().equals(AES_128_CTR) && !crypto.getKdf().equals(SCRYPT)) {
throw new CipherException("KDF type is not supported");
}
}
public static byte[] generateRandomBytes(int size) {
byte[] bytes = new byte[size];
new SecureRandom().nextBytes(bytes);
return bytes;
}
}