-
Notifications
You must be signed in to change notification settings - Fork 40.2k
/
PrivateKeyParser.java
397 lines (330 loc) · 11.8 KB
/
PrivateKeyParser.java
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.web.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.boot.web.server.PrivateKeyParser.DerElement.TagType;
import org.springframework.boot.web.server.PrivateKeyParser.DerElement.ValueType;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
/**
* Parser for PKCS private key files in PEM format.
*
* @author Scott Frederick
* @author Phillip Webb
* @author Moritz Halbritter
*/
final class PrivateKeyParser {
private static final String PKCS1_HEADER = "-+BEGIN\\s+RSA\\s+PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+";
private static final String PKCS1_FOOTER = "-+END\\s+RSA\\s+PRIVATE\\s+KEY[^-]*-+";
private static final String PKCS8_HEADER = "-+BEGIN\\s+PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+";
private static final String PKCS8_FOOTER = "-+END\\s+PRIVATE\\s+KEY[^-]*-+";
private static final String EC_HEADER = "-+BEGIN\\s+EC\\s+PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+";
private static final String EC_FOOTER = "-+END\\s+EC\\s+PRIVATE\\s+KEY[^-]*-+";
private static final String BASE64_TEXT = "([a-z0-9+/=\\r\\n]+)";
private static final List<PemParser> PEM_PARSERS;
static {
List<PemParser> parsers = new ArrayList<>();
parsers.add(new PemParser(PKCS1_HEADER, PKCS1_FOOTER, PrivateKeyParser::createKeySpecForPkcs1, "RSA"));
parsers.add(new PemParser(EC_HEADER, EC_FOOTER, PrivateKeyParser::createKeySpecForEc, "EC"));
parsers.add(new PemParser(PKCS8_HEADER, PKCS8_FOOTER, PKCS8EncodedKeySpec::new, "RSA", "EC", "DSA"));
PEM_PARSERS = Collections.unmodifiableList(parsers);
}
/**
* ASN.1 encoded object identifier {@literal 1.2.840.113549.1.1.1}.
*/
private static final int[] RSA_ALGORITHM = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };
/**
* ASN.1 encoded object identifier {@literal 1.2.840.10045.2.1}.
*/
private static final int[] EC_ALGORITHM = { 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01 };
/**
* ASN.1 encoded object identifier {@literal 1.3.132.0.34}.
*/
private static final int[] EC_PARAMETERS = { 0x2b, 0x81, 0x04, 0x00, 0x22 };
private PrivateKeyParser() {
}
private static PKCS8EncodedKeySpec createKeySpecForPkcs1(byte[] bytes) {
return createKeySpecForAlgorithm(bytes, RSA_ALGORITHM, null);
}
private static PKCS8EncodedKeySpec createKeySpecForEc(byte[] bytes) {
DerElement ecPrivateKey = DerElement.of(bytes);
Assert.state(ecPrivateKey.isType(ValueType.ENCODED, TagType.SEQUENCE),
"Key spec should be an ASN.1 encoded sequence");
DerElement version = DerElement.of(ecPrivateKey.getContents());
Assert.state(version != null && version.isType(ValueType.PRIMITIVE, TagType.INTEGER),
"Key spec should start with version");
Assert.state(version.getContents().remaining() == 1 && version.getContents().get() == 1,
"Key spec version must be 1");
DerElement privateKey = DerElement.of(ecPrivateKey.getContents());
Assert.state(privateKey != null && privateKey.isType(ValueType.PRIMITIVE, TagType.OCTET_STRING),
"Key spec should contain private key");
DerElement parameters = DerElement.of(ecPrivateKey.getContents());
return createKeySpecForAlgorithm(bytes, EC_ALGORITHM, getEcParameters(parameters));
}
private static int[] getEcParameters(DerElement parameters) {
if (parameters == null) {
return EC_PARAMETERS;
}
Assert.state(parameters.isType(ValueType.ENCODED), "Key spec should contain encoded parameters");
DerElement contents = DerElement.of(parameters.getContents());
Assert.state(contents.isType(ValueType.PRIMITIVE, TagType.OBJECT_IDENTIFIER),
"Key spec parameters should contain object identifier");
return getEcParameters(contents.getContents());
}
private static int[] getEcParameters(ByteBuffer bytes) {
int[] result = new int[bytes.remaining()];
for (int i = 0; i < result.length; i++) {
result[i] = bytes.get() & 0xFF;
}
return result;
}
private static PKCS8EncodedKeySpec createKeySpecForAlgorithm(byte[] bytes, int[] algorithm, int[] parameters) {
try {
DerEncoder encoder = new DerEncoder();
encoder.integer(0x00); // Version 0
DerEncoder algorithmIdentifier = new DerEncoder();
algorithmIdentifier.objectIdentifier(algorithm);
algorithmIdentifier.objectIdentifier(parameters);
encoder.sequence(algorithmIdentifier.toByteArray());
encoder.octetString(bytes);
return new PKCS8EncodedKeySpec(encoder.toSequence());
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
/**
* Load a private key from the specified resource.
* @param resource the private key to parse
* @return the parsed private key
*/
static PrivateKey parse(String resource) {
try {
String text = readText(resource);
for (PemParser pemParser : PEM_PARSERS) {
PrivateKey privateKey = pemParser.parse(text);
if (privateKey != null) {
return privateKey;
}
}
throw new IllegalStateException("Unrecognized private key format");
}
catch (Exception ex) {
throw new IllegalStateException("Error loading private key file " + resource, ex);
}
}
private static String readText(String resource) throws IOException {
URL url = ResourceUtils.getURL(resource);
try (Reader reader = new InputStreamReader(url.openStream())) {
return FileCopyUtils.copyToString(reader);
}
}
/**
* Parser for a specific PEM format.
*/
private static class PemParser {
private final Pattern pattern;
private final Function<byte[], PKCS8EncodedKeySpec> keySpecFactory;
private final String[] algorithms;
PemParser(String header, String footer, Function<byte[], PKCS8EncodedKeySpec> keySpecFactory,
String... algorithms) {
this.pattern = Pattern.compile(header + BASE64_TEXT + footer, Pattern.CASE_INSENSITIVE);
this.algorithms = algorithms;
this.keySpecFactory = keySpecFactory;
}
PrivateKey parse(String text) {
Matcher matcher = this.pattern.matcher(text);
return (!matcher.find()) ? null : parse(decodeBase64(matcher.group(1)));
}
private static byte[] decodeBase64(String content) {
byte[] contentBytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes();
return Base64Utils.decode(contentBytes);
}
private PrivateKey parse(byte[] bytes) {
try {
PKCS8EncodedKeySpec keySpec = this.keySpecFactory.apply(bytes);
for (String algorithm : this.algorithms) {
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
try {
return keyFactory.generatePrivate(keySpec);
}
catch (InvalidKeySpecException ex) {
}
}
return null;
}
catch (GeneralSecurityException ex) {
throw new IllegalArgumentException("Unexpected key format", ex);
}
}
}
/**
* Simple ASN.1 DER encoder.
*/
static class DerEncoder {
private final ByteArrayOutputStream stream = new ByteArrayOutputStream();
void objectIdentifier(int... encodedObjectIdentifier) throws IOException {
int code = (encodedObjectIdentifier != null) ? 0x06 : 0x05;
codeLengthBytes(code, bytes(encodedObjectIdentifier));
}
void integer(int... encodedInteger) throws IOException {
codeLengthBytes(0x02, bytes(encodedInteger));
}
void octetString(byte[] bytes) throws IOException {
codeLengthBytes(0x04, bytes);
}
void sequence(int... elements) throws IOException {
sequence(bytes(elements));
}
void sequence(byte[] bytes) throws IOException {
codeLengthBytes(0x30, bytes);
}
void codeLengthBytes(int code, byte[] bytes) throws IOException {
this.stream.write(code);
int length = (bytes != null) ? bytes.length : 0;
if (length <= 127) {
this.stream.write(length & 0xFF);
}
else {
ByteArrayOutputStream lengthStream = new ByteArrayOutputStream();
while (length != 0) {
lengthStream.write(length & 0xFF);
length = length >> 8;
}
byte[] lengthBytes = lengthStream.toByteArray();
this.stream.write(0x80 | lengthBytes.length);
for (int i = lengthBytes.length - 1; i >= 0; i--) {
this.stream.write(lengthBytes[i]);
}
}
if (bytes != null) {
this.stream.write(bytes);
}
}
private static byte[] bytes(int... elements) {
if (elements == null) {
return null;
}
byte[] result = new byte[elements.length];
for (int i = 0; i < elements.length; i++) {
result[i] = (byte) elements[i];
}
return result;
}
byte[] toSequence() throws IOException {
DerEncoder sequenceEncoder = new DerEncoder();
sequenceEncoder.sequence(toByteArray());
return sequenceEncoder.toByteArray();
}
byte[] toByteArray() {
return this.stream.toByteArray();
}
}
/**
* An ASN.1 DER encoded element.
*/
static final class DerElement {
private final ValueType valueType;
private final long tagType;
private ByteBuffer contents;
private DerElement(ByteBuffer bytes) {
byte b = bytes.get();
this.valueType = ((b & 0x20) == 0) ? ValueType.PRIMITIVE : ValueType.ENCODED;
this.tagType = decodeTagType(b, bytes);
int length = decodeLength(bytes);
bytes.limit(bytes.position() + length);
this.contents = bytes.slice();
bytes.limit(bytes.capacity());
bytes.position(bytes.position() + length);
}
private long decodeTagType(byte b, ByteBuffer bytes) {
long tagType = (b & 0x1F);
if (tagType != 0x1F) {
return tagType;
}
tagType = 0;
b = bytes.get();
while ((b & 0x80) != 0) {
tagType <<= 7;
tagType = tagType | (b & 0x7F);
b = bytes.get();
}
return tagType;
}
private int decodeLength(ByteBuffer bytes) {
byte b = bytes.get();
if ((b & 0x80) == 0) {
return b & 0x7F;
}
int numberOfLengthBytes = (b & 0x7F);
Assert.state(numberOfLengthBytes != 0, "Infinite length encoding is not supported");
Assert.state(numberOfLengthBytes != 0x7F, "Reserved length encoding is not supported");
Assert.state(numberOfLengthBytes <= 4, "Length overflow");
int length = 0;
for (int i = 0; i < numberOfLengthBytes; i++) {
length <<= 8;
length |= (bytes.get() & 0xFF);
}
return length;
}
boolean isType(ValueType valueType) {
return this.valueType == valueType;
}
boolean isType(ValueType valueType, TagType tagType) {
return this.valueType == valueType && this.tagType == tagType.getNumber();
}
ByteBuffer getContents() {
return this.contents;
}
static DerElement of(byte[] bytes) {
return of(ByteBuffer.wrap(bytes));
}
static DerElement of(ByteBuffer bytes) {
return (bytes.remaining() > 0) ? new DerElement(bytes) : null;
}
enum ValueType {
PRIMITIVE, ENCODED
}
enum TagType {
INTEGER(0x02), OCTET_STRING(0x04), OBJECT_IDENTIFIER(0x06), SEQUENCE(0x10);
private final int number;
TagType(int number) {
this.number = number;
}
int getNumber() {
return this.number;
}
}
}
}