-
Notifications
You must be signed in to change notification settings - Fork 1
/
PKCS8PEM.java
164 lines (147 loc) · 6.1 KB
/
PKCS8PEM.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
/*
* Copyright (C) 2017 DV Bern AG, Switzerland
*
* 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
*
* http://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 ch.dvbern.lib.cryptutil.fileformats;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import ch.dvbern.lib.cryptutil.annotations.NonNull;
import ch.dvbern.lib.cryptutil.annotations.Nullable;
import static java.util.Objects.requireNonNull;
/**
* Supports PKCS#8 public and privte keys, with and without password.
*
* You can determine if your file is in the correct format by looking at the file header:
*
* Valid headers (exact match required!):
* <pre>
* -----BEGIN PUBLIC KEY-----
* -----BEGIN PRIVATE KEY-----
* -----BEGIN ENCRYPTED PRIVATE KEY-----
* </pre>
*
* In converting between key formats, google + openssl is your friend :)
*/
public final class PKCS8PEM {
// header/footer for a PKCS#8 encoded PEM file without password/encryption
private static final Pattern PEM_KEY_PATTERN =
Pattern.compile("^-----(BEGIN|END) (ENCRYPTED )?(PRIVATE|PUBLIC) KEY-----\\s*$");
private static final String ALGO_RSA = "RSA";
/**
* Very(!) simple and non-forgiving parsing method:
* extracts the Base64 encoded payload of the PEM file
* and then base64 decodes it to get the raw key.
*
* @param pkcs8pem ownership is not taken, caller needs to close the stream
*/
private @NonNull byte[] parseKeyFromPKCS8PEM(@NonNull InputStream pkcs8pem) {
requireNonNull(pkcs8pem);
BufferedReader br =
new BufferedReader(new InputStreamReader(pkcs8pem, StandardCharsets.UTF_8));
String content = br.lines()
.filter(line -> !line.isEmpty())
.filter(line -> !PEM_KEY_PATTERN.matcher(line).matches())
.collect(Collectors.joining("\r\n"));
byte[] keyBytes = Base64.getMimeDecoder().decode(content);
return keyBytes;
}
/**
* @param privateKey ownership is not taken, caller needs to close the stream
*/
public @NonNull RSAPrivateKey readKeyFromPKCS8EncodedPEM(
@NonNull InputStream privateKey,
@Nullable char[] password
) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException {
requireNonNull(privateKey);
@NonNull byte[] keyData = parseKeyFromPKCS8PEM(privateKey);
@NonNull RSAPrivateKey rsaPrivateKey;
if (password != null) {
rsaPrivateKey = createFromPKCS8EndocdedRSAKey(keyData, password);
} else {
rsaPrivateKey = createFromPKCS8EndocdedRSAKey(keyData);
}
return rsaPrivateKey;
}
/**
* @param pkcs8pem ownership is not taken, caller needs to close the stream
*/
public @NonNull RSAPublicKey readCertFromPKCS8EncodedPEM(@NonNull InputStream pkcs8pem)
throws NoSuchAlgorithmException, InvalidKeySpecException {
@NonNull byte[] keyData = parseKeyFromPKCS8PEM(pkcs8pem);
return createFromX509EncodedRSACert(keyData);
}
private @NonNull RSAPublicKey createFromX509EncodedRSACert(@NonNull byte[] publicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory kf = KeyFactory.getInstance(ALGO_RSA);
RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(publicKey));
return pubKey;
}
private @NonNull RSAPrivateKey createFromPKCS8EndocdedRSAKey(@NonNull byte[] privateKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory kf = KeyFactory.getInstance(ALGO_RSA);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
return privKey;
}
private @NonNull RSAPrivateKey createFromPKCS8EndocdedRSAKey(
@NonNull byte[] privateKey,
@NonNull char[] password
) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException {
requireNonNull(privateKey);
requireNonNull(password);
EncryptedPrivateKeyInfo ePKInfo = new EncryptedPrivateKeyInfo(privateKey);
Cipher cipher = Cipher.getInstance(ePKInfo.getAlgName());
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
// Now create the Key from the PBEKeySpec
SecretKeyFactory skFac = SecretKeyFactory.getInstance(ePKInfo.getAlgName());
Key pbeKey = skFac.generateSecret(pbeKeySpec);
// Extract the iteration count and the salt
AlgorithmParameters algParams = ePKInfo.getAlgParameters();
cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
// Decrypt the encryped private key into a PKCS8EncodedKeySpec
KeySpec pkcs8KeySpec = ePKInfo.getKeySpec(cipher);
// Now retrieve the RSA Public and private keys by using an
// RSA keyfactory.
KeyFactory rsaKeyFac = KeyFactory.getInstance(ALGO_RSA);
// First get the private key
RSAPrivateCrtKey rsaPriv = (RSAPrivateCrtKey) rsaKeyFac.generatePrivate(pkcs8KeySpec);
return rsaPriv;
}
}