Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/sun/security/provider/KeyProtector.java
41159 views
1
/*
2
* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package sun.security.provider;
27
28
import java.io.IOException;
29
import java.security.Key;
30
import java.security.KeyStoreException;
31
import java.security.MessageDigest;
32
import java.security.NoSuchAlgorithmException;
33
import java.security.SecureRandom;
34
import java.security.UnrecoverableKeyException;
35
import java.util.*;
36
37
import sun.security.pkcs.PKCS8Key;
38
import sun.security.pkcs.EncryptedPrivateKeyInfo;
39
import sun.security.x509.AlgorithmId;
40
import sun.security.util.ObjectIdentifier;
41
import sun.security.util.KnownOIDs;
42
import sun.security.util.DerValue;
43
44
/**
45
* This is an implementation of a Sun proprietary, exportable algorithm
46
* intended for use when protecting (or recovering the cleartext version of)
47
* sensitive keys.
48
* This algorithm is not intended as a general purpose cipher.
49
*
50
* This is how the algorithm works for key protection:
51
*
52
* p - user password
53
* s - random salt
54
* X - xor key
55
* P - to-be-protected key
56
* Y - protected key
57
* R - what gets stored in the keystore
58
*
59
* Step 1:
60
* Take the user's password, append a random salt (of fixed size) to it,
61
* and hash it: d1 = digest(p, s)
62
* Store d1 in X.
63
*
64
* Step 2:
65
* Take the user's password, append the digest result from the previous step,
66
* and hash it: dn = digest(p, dn-1).
67
* Store dn in X (append it to the previously stored digests).
68
* Repeat this step until the length of X matches the length of the private key
69
* P.
70
*
71
* Step 3:
72
* XOR X and P, and store the result in Y: Y = X XOR P.
73
*
74
* Step 4:
75
* Store s, Y, and digest(p, P) in the result buffer R:
76
* R = s + Y + digest(p, P), where "+" denotes concatenation.
77
* (NOTE: digest(p, P) is stored in the result buffer, so that when the key is
78
* recovered, we can check if the recovered key indeed matches the original
79
* key.) R is stored in the keystore.
80
*
81
* The protected key is recovered as follows:
82
*
83
* Step1 and Step2 are the same as above, except that the salt is not randomly
84
* generated, but taken from the result R of step 4 (the first length(s)
85
* bytes).
86
*
87
* Step 3 (XOR operation) yields the plaintext key.
88
*
89
* Then concatenate the password with the recovered key, and compare with the
90
* last length(digest(p, P)) bytes of R. If they match, the recovered key is
91
* indeed the same key as the original key.
92
*
93
* @author Jan Luehe
94
*
95
*
96
* @see java.security.KeyStore
97
* @see JavaKeyStore
98
* @see KeyTool
99
*
100
* @since 1.2
101
*/
102
103
final class KeyProtector {
104
105
private static final int SALT_LEN = 20; // the salt length
106
private static final String DIGEST_ALG = "SHA";
107
private static final int DIGEST_LEN = 20;
108
109
// The password used for protecting/recovering keys passed through this
110
// key protector. We store it as a byte array, so that we can digest it.
111
private byte[] passwdBytes;
112
113
private MessageDigest md;
114
115
116
/**
117
* Creates an instance of this class, and initializes it with the given
118
* password.
119
*/
120
public KeyProtector(byte[] passwordBytes)
121
throws NoSuchAlgorithmException
122
{
123
if (passwordBytes == null) {
124
throw new IllegalArgumentException("password can't be null");
125
}
126
md = MessageDigest.getInstance(DIGEST_ALG);
127
this.passwdBytes = passwordBytes;
128
}
129
130
/*
131
* Protects the given plaintext key, using the password provided at
132
* construction time.
133
*/
134
public byte[] protect(Key key) throws KeyStoreException
135
{
136
int i;
137
int numRounds;
138
byte[] digest;
139
int xorOffset; // offset in xorKey where next digest will be stored
140
int encrKeyOffset = 0;
141
142
if (key == null) {
143
throw new IllegalArgumentException("plaintext key can't be null");
144
}
145
146
if (!"PKCS#8".equalsIgnoreCase(key.getFormat())) {
147
throw new KeyStoreException(
148
"Cannot get key bytes, not PKCS#8 encoded");
149
}
150
151
byte[] plainKey = key.getEncoded();
152
if (plainKey == null) {
153
throw new KeyStoreException(
154
"Cannot get key bytes, encoding not supported");
155
}
156
157
// Determine the number of digest rounds
158
numRounds = plainKey.length / DIGEST_LEN;
159
if ((plainKey.length % DIGEST_LEN) != 0)
160
numRounds++;
161
162
// Create a random salt
163
byte[] salt = new byte[SALT_LEN];
164
SecureRandom random = new SecureRandom();
165
random.nextBytes(salt);
166
167
// Set up the byte array which will be XORed with "plainKey"
168
byte[] xorKey = new byte[plainKey.length];
169
170
// Compute the digests, and store them in "xorKey"
171
for (i = 0, xorOffset = 0, digest = salt;
172
i < numRounds;
173
i++, xorOffset += DIGEST_LEN) {
174
md.update(passwdBytes);
175
md.update(digest);
176
digest = md.digest();
177
md.reset();
178
// Copy the digest into "xorKey"
179
if (i < numRounds - 1) {
180
System.arraycopy(digest, 0, xorKey, xorOffset,
181
digest.length);
182
} else {
183
System.arraycopy(digest, 0, xorKey, xorOffset,
184
xorKey.length - xorOffset);
185
}
186
}
187
188
// XOR "plainKey" with "xorKey", and store the result in "tmpKey"
189
byte[] tmpKey = new byte[plainKey.length];
190
for (i = 0; i < tmpKey.length; i++) {
191
tmpKey[i] = (byte)(plainKey[i] ^ xorKey[i]);
192
}
193
194
// Store salt and "tmpKey" in "encrKey"
195
byte[] encrKey = new byte[salt.length + tmpKey.length + DIGEST_LEN];
196
System.arraycopy(salt, 0, encrKey, encrKeyOffset, salt.length);
197
encrKeyOffset += salt.length;
198
System.arraycopy(tmpKey, 0, encrKey, encrKeyOffset, tmpKey.length);
199
encrKeyOffset += tmpKey.length;
200
201
// Append digest(password, plainKey) as an integrity check to "encrKey"
202
md.update(passwdBytes);
203
Arrays.fill(passwdBytes, (byte)0x00);
204
passwdBytes = null;
205
md.update(plainKey);
206
digest = md.digest();
207
md.reset();
208
System.arraycopy(digest, 0, encrKey, encrKeyOffset, digest.length);
209
Arrays.fill(plainKey, (byte)0);
210
211
// wrap the protected private key in a PKCS#8-style
212
// EncryptedPrivateKeyInfo, and returns its encoding
213
AlgorithmId encrAlg;
214
try {
215
encrAlg = new AlgorithmId(ObjectIdentifier.of
216
(KnownOIDs.JAVASOFT_JDKKeyProtector));
217
return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded();
218
} catch (IOException ioe) {
219
throw new KeyStoreException(ioe.getMessage());
220
}
221
}
222
223
/*
224
* Recovers the plaintext version of the given key (in protected format),
225
* using the password provided at construction time.
226
*/
227
public Key recover(EncryptedPrivateKeyInfo encrInfo)
228
throws UnrecoverableKeyException
229
{
230
int i;
231
byte[] digest;
232
int numRounds;
233
int xorOffset; // offset in xorKey where next digest will be stored
234
int encrKeyLen; // the length of the encrpyted key
235
236
// do we support the algorithm?
237
AlgorithmId encrAlg = encrInfo.getAlgorithm();
238
if (!(encrAlg.getOID().toString().equals
239
(KnownOIDs.JAVASOFT_JDKKeyProtector.value()))) {
240
throw new UnrecoverableKeyException("Unsupported key protection "
241
+ "algorithm");
242
}
243
244
byte[] protectedKey = encrInfo.getEncryptedData();
245
246
/*
247
* Get the salt associated with this key (the first SALT_LEN bytes of
248
* <code>protectedKey</code>)
249
*/
250
byte[] salt = new byte[SALT_LEN];
251
System.arraycopy(protectedKey, 0, salt, 0, SALT_LEN);
252
253
// Determine the number of digest rounds
254
encrKeyLen = protectedKey.length - SALT_LEN - DIGEST_LEN;
255
numRounds = encrKeyLen / DIGEST_LEN;
256
if ((encrKeyLen % DIGEST_LEN) != 0) numRounds++;
257
258
// Get the encrypted key portion and store it in "encrKey"
259
byte[] encrKey = new byte[encrKeyLen];
260
System.arraycopy(protectedKey, SALT_LEN, encrKey, 0, encrKeyLen);
261
262
// Set up the byte array which will be XORed with "encrKey"
263
byte[] xorKey = new byte[encrKey.length];
264
265
// Compute the digests, and store them in "xorKey"
266
for (i = 0, xorOffset = 0, digest = salt;
267
i < numRounds;
268
i++, xorOffset += DIGEST_LEN) {
269
md.update(passwdBytes);
270
md.update(digest);
271
digest = md.digest();
272
md.reset();
273
// Copy the digest into "xorKey"
274
if (i < numRounds - 1) {
275
System.arraycopy(digest, 0, xorKey, xorOffset,
276
digest.length);
277
} else {
278
System.arraycopy(digest, 0, xorKey, xorOffset,
279
xorKey.length - xorOffset);
280
}
281
}
282
283
// XOR "encrKey" with "xorKey", and store the result in "plainKey"
284
byte[] plainKey = new byte[encrKey.length];
285
for (i = 0; i < plainKey.length; i++) {
286
plainKey[i] = (byte)(encrKey[i] ^ xorKey[i]);
287
}
288
289
/*
290
* Check the integrity of the recovered key by concatenating it with
291
* the password, digesting the concatenation, and comparing the
292
* result of the digest operation with the digest provided at the end
293
* of <code>protectedKey</code>. If the two digest values are
294
* different, throw an exception.
295
*/
296
md.update(passwdBytes);
297
Arrays.fill(passwdBytes, (byte)0x00);
298
passwdBytes = null;
299
md.update(plainKey);
300
digest = md.digest();
301
md.reset();
302
for (i = 0; i < digest.length; i++) {
303
if (digest[i] != protectedKey[SALT_LEN + encrKeyLen + i]) {
304
throw new UnrecoverableKeyException("Cannot recover key");
305
}
306
}
307
308
// The parseKey() method of PKCS8Key parses the key
309
// algorithm and instantiates the appropriate key factory,
310
// which in turn parses the key material.
311
try {
312
return PKCS8Key.parseKey(plainKey);
313
} catch (IOException ioe) {
314
throw new UnrecoverableKeyException(ioe.getMessage());
315
} finally {
316
Arrays.fill(plainKey, (byte)0);
317
}
318
}
319
}
320
321