Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/sun/security/pkcs/PKCS8Key.java
41159 views
1
/*
2
* Copyright (c) 1996, 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.pkcs;
27
28
import java.io.*;
29
import java.security.Key;
30
import java.security.KeyRep;
31
import java.security.PrivateKey;
32
import java.security.KeyFactory;
33
import java.security.MessageDigest;
34
import java.security.InvalidKeyException;
35
import java.security.NoSuchAlgorithmException;
36
import java.security.spec.InvalidKeySpecException;
37
import java.security.spec.PKCS8EncodedKeySpec;
38
import java.util.Arrays;
39
40
import jdk.internal.access.SharedSecrets;
41
import sun.security.x509.*;
42
import sun.security.util.*;
43
44
/**
45
* Holds a PKCS#8 key, for example a private key
46
*
47
* According to https://tools.ietf.org/html/rfc5958:
48
*
49
* OneAsymmetricKey ::= SEQUENCE {
50
* version Version,
51
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
52
* privateKey PrivateKey,
53
* attributes [0] Attributes OPTIONAL,
54
* ...,
55
* [[2: publicKey [1] PublicKey OPTIONAL ]],
56
* ...
57
* }
58
*
59
* We support this format but do not parse attributes and publicKey now.
60
*/
61
public class PKCS8Key implements PrivateKey {
62
63
/** use serialVersionUID from JDK 1.1. for interoperability */
64
@java.io.Serial
65
private static final long serialVersionUID = -3836890099307167124L;
66
67
/* The algorithm information (name, parameters, etc). */
68
protected AlgorithmId algid;
69
70
/* The key bytes, without the algorithm information */
71
protected byte[] key;
72
73
/* The encoded for the key. Created on demand by encode(). */
74
protected byte[] encodedKey;
75
76
/* The version for this key */
77
private static final int V1 = 0;
78
private static final int V2 = 1;
79
80
/**
81
* Default constructor. Constructors in sub-classes that create a new key
82
* from its components require this. These constructors must initialize
83
* {@link #algid} and {@link #key}.
84
*/
85
protected PKCS8Key() { }
86
87
/**
88
* Another constructor. Constructors in sub-classes that create a new key
89
* from an encoded byte array require this. We do not assign this
90
* encoding to {@link #encodedKey} directly.
91
*
92
* This method is also used by {@link #parseKey} to create a raw key.
93
*/
94
protected PKCS8Key(byte[] input) throws InvalidKeyException {
95
decode(new ByteArrayInputStream(input));
96
}
97
98
private void decode(InputStream is) throws InvalidKeyException {
99
DerValue val = null;
100
try {
101
val = new DerValue(is);
102
if (val.tag != DerValue.tag_Sequence) {
103
throw new InvalidKeyException("invalid key format");
104
}
105
106
int version = val.data.getInteger();
107
if (version != V1 && version != V2) {
108
throw new InvalidKeyException("unknown version: " + version);
109
}
110
algid = AlgorithmId.parse (val.data.getDerValue ());
111
key = val.data.getOctetString();
112
113
DerValue next;
114
if (val.data.available() == 0) {
115
return;
116
}
117
next = val.data.getDerValue();
118
if (next.isContextSpecific((byte)0)) {
119
if (val.data.available() == 0) {
120
return;
121
}
122
next = val.data.getDerValue();
123
}
124
125
if (next.isContextSpecific((byte)1)) {
126
if (version == V1) {
127
throw new InvalidKeyException("publicKey seen in v1");
128
}
129
if (val.data.available() == 0) {
130
return;
131
}
132
}
133
throw new InvalidKeyException("Extra bytes");
134
} catch (IOException e) {
135
throw new InvalidKeyException("IOException : " + e.getMessage());
136
} finally {
137
if (val != null) {
138
val.clear();
139
}
140
}
141
}
142
143
/**
144
* Construct PKCS#8 subject public key from a DER encoding. If a
145
* security provider supports the key algorithm with a specific class,
146
* a PrivateKey from the provider is returned. Otherwise, a raw
147
* PKCS8Key object is returned.
148
*
149
* <P>This mechanism guarantees that keys (and algorithms) may be
150
* freely manipulated and transferred, without risk of losing
151
* information. Also, when a key (or algorithm) needs some special
152
* handling, that specific need can be accommodated.
153
*
154
* @param encoded the DER-encoded SubjectPublicKeyInfo value
155
* @exception IOException on data format errors
156
*/
157
public static PrivateKey parseKey(byte[] encoded) throws IOException {
158
try {
159
PKCS8Key rawKey = new PKCS8Key(encoded);
160
byte[] internal = rawKey.getEncodedInternal();
161
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(internal);
162
PrivateKey result = null;
163
try {
164
result = KeyFactory.getInstance(rawKey.algid.getName())
165
.generatePrivate(pkcs8KeySpec);
166
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
167
// Ignore and return raw key
168
result = rawKey;
169
} finally {
170
if (result != rawKey) {
171
rawKey.clear();
172
}
173
SharedSecrets.getJavaSecuritySpecAccess()
174
.clearEncodedKeySpec(pkcs8KeySpec);
175
}
176
return result;
177
} catch (InvalidKeyException e) {
178
throw new IOException("corrupt private key", e);
179
}
180
}
181
182
/**
183
* Returns the algorithm to be used with this key.
184
*/
185
public String getAlgorithm() {
186
return algid.getName();
187
}
188
189
/**
190
* Returns the algorithm ID to be used with this key.
191
*/
192
public AlgorithmId getAlgorithmId () {
193
return algid;
194
}
195
196
/**
197
* Returns the DER-encoded form of the key as a byte array,
198
* or {@code null} if an encoding error occurs.
199
*/
200
public byte[] getEncoded() {
201
byte[] b = getEncodedInternal();
202
return (b == null) ? null : b.clone();
203
}
204
205
/**
206
* Returns the format for this key: "PKCS#8"
207
*/
208
public String getFormat() {
209
return "PKCS#8";
210
}
211
212
/**
213
* DER-encodes this key as a byte array stored inside this object
214
* and return it.
215
*
216
* @return the encoding, or null if there is an I/O error.
217
*/
218
private synchronized byte[] getEncodedInternal() {
219
if (encodedKey == null) {
220
try {
221
DerOutputStream tmp = new DerOutputStream();
222
tmp.putInteger(V1);
223
algid.encode(tmp);
224
tmp.putOctetString(key);
225
DerValue out = DerValue.wrap(DerValue.tag_Sequence, tmp);
226
encodedKey = out.toByteArray();
227
out.clear();
228
} catch (IOException e) {
229
// encodedKey is still null
230
}
231
}
232
return encodedKey;
233
}
234
235
@java.io.Serial
236
protected Object writeReplace() throws java.io.ObjectStreamException {
237
return new KeyRep(KeyRep.Type.PRIVATE,
238
getAlgorithm(),
239
getFormat(),
240
getEncodedInternal());
241
}
242
243
/**
244
* We used to serialize a PKCS8Key as itself (instead of a KeyRep).
245
*/
246
@java.io.Serial
247
private void readObject(ObjectInputStream stream) throws IOException {
248
try {
249
decode(stream);
250
} catch (InvalidKeyException e) {
251
throw new IOException("deserialized key is invalid: " +
252
e.getMessage());
253
}
254
}
255
256
/**
257
* Compares two private keys. This returns false if the object with which
258
* to compare is not of type <code>Key</code>.
259
* Otherwise, the encoding of this key object is compared with the
260
* encoding of the given key object.
261
*
262
* @param object the object with which to compare
263
* @return {@code true} if this key has the same encoding as the
264
* object argument; {@code false} otherwise.
265
*/
266
public boolean equals(Object object) {
267
if (this == object) {
268
return true;
269
}
270
if (object instanceof PKCS8Key) {
271
// time-constant comparison
272
return MessageDigest.isEqual(
273
getEncodedInternal(),
274
((PKCS8Key)object).getEncodedInternal());
275
} else if (object instanceof Key) {
276
// time-constant comparison
277
byte[] otherEncoded = ((Key)object).getEncoded();
278
try {
279
return MessageDigest.isEqual(
280
getEncodedInternal(),
281
otherEncoded);
282
} finally {
283
if (otherEncoded != null) {
284
Arrays.fill(otherEncoded, (byte) 0);
285
}
286
}
287
}
288
return false;
289
}
290
291
/**
292
* Calculates a hash code value for this object. Objects
293
* which are equal will also have the same hashcode.
294
*/
295
public int hashCode() {
296
return Arrays.hashCode(getEncodedInternal());
297
}
298
299
public void clear() {
300
if (encodedKey != null) {
301
Arrays.fill(encodedKey, (byte)0);
302
}
303
Arrays.fill(key, (byte)0);
304
}
305
}
306
307