forked from jruby/jruby-openssl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPKey.java
More file actions
409 lines (378 loc) · 20.2 KB
/
PKey.java
File metadata and controls
409 lines (378 loc) · 20.2 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
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
398
399
400
401
402
403
404
405
406
407
408
409
/***** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.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.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2010 Hiroshi Nakamura <nahi@ruby-lang.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext.openssl.impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.spec.DHParameterSpec;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DLSequence;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.DSAParameter;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.jruby.ext.openssl.SecurityHelper;
/**
*
* Handles PKey related ASN.1 handling.
*
* @author <a href="mailto:nahi@ruby-lang.org">Hiroshi Nakamura</a>
*/
public class PKey {
public enum Type { RSA, DSA, EC; }
public static KeyPair readPrivateKey(final Type type, final byte[] input)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
return readPrivateKey(type, mockPrivateKeyInfo(type, input));
}
private static PrivateKeyInfo mockPrivateKeyInfo(final Type type, final byte[] input) throws IOException {
assert type != null;
return new PrivateKeyInfo(null, new ASN1InputStream(input).readObject());
}
public static KeyPair readPrivateKey(final Type type, final PrivateKeyInfo keyInfo)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
KeySpec pubSpec; KeySpec privSpec; ASN1Sequence seq;
switch (type) {
case RSA:
seq = (ASN1Sequence) keyInfo.parsePrivateKey();
ASN1Integer mod = (ASN1Integer) seq.getObjectAt(1);
ASN1Integer pubExp = (ASN1Integer) seq.getObjectAt(2);
ASN1Integer privExp = (ASN1Integer) seq.getObjectAt(3);
ASN1Integer p1 = (ASN1Integer) seq.getObjectAt(4);
ASN1Integer p2 = (ASN1Integer) seq.getObjectAt(5);
ASN1Integer exp1 = (ASN1Integer) seq.getObjectAt(6);
ASN1Integer exp2 = (ASN1Integer) seq.getObjectAt(7);
ASN1Integer crtCoef = (ASN1Integer) seq.getObjectAt(8);
pubSpec = new RSAPublicKeySpec(mod.getValue(), pubExp.getValue());
privSpec = new RSAPrivateCrtKeySpec(
mod.getValue(), pubExp.getValue(), privExp.getValue(),
p1.getValue(), p2.getValue(),
exp1.getValue(), exp2.getValue(), crtCoef.getValue());
break;
case DSA:
final ASN1Encodable parsedDSAKey = keyInfo.parsePrivateKey();
if (parsedDSAKey instanceof ASN1Integer) {
// PKCS#8 format: private key is just x (INTEGER), params in AlgorithmIdentifier
final BigInteger xVal = ((ASN1Integer) parsedDSAKey).getValue();
final DSAParameter dsaParam = DSAParameter.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
final BigInteger pVal = dsaParam.getP();
final BigInteger qVal = dsaParam.getQ();
final BigInteger gVal = dsaParam.getG();
final BigInteger yVal = gVal.modPow(xVal, pVal);
privSpec = new DSAPrivateKeySpec(xVal, pVal, qVal, gVal);
pubSpec = new DSAPublicKeySpec(yVal, pVal, qVal, gVal);
} else {
// Traditional "DSA PRIVATE KEY" format: SEQUENCE { version, p, q, g, y, x }
seq = (ASN1Sequence) parsedDSAKey;
ASN1Integer p = (ASN1Integer) seq.getObjectAt(1);
ASN1Integer q = (ASN1Integer) seq.getObjectAt(2);
ASN1Integer g = (ASN1Integer) seq.getObjectAt(3);
ASN1Integer y = (ASN1Integer) seq.getObjectAt(4);
ASN1Integer x = (ASN1Integer) seq.getObjectAt(5);
privSpec = new DSAPrivateKeySpec(x.getValue(), p.getValue(), q.getValue(), g.getValue());
pubSpec = new DSAPublicKeySpec(y.getValue(), p.getValue(), q.getValue(), g.getValue());
}
break;
case EC:
return readECPrivateKey(SecurityHelper.getKeyFactory("EC"), keyInfo);
default:
throw new AssertionError("unexpected key type: " + type);
}
final KeyFactory keyFactory = SecurityHelper.getKeyFactory(type.name());
return new KeyPair(keyFactory.generatePublic(pubSpec), keyFactory.generatePrivate(privSpec));
}
// d2i_PUBKEY_bio
public static PublicKey readPublicKey(final byte[] input) throws IOException {
// Try PEM first
try (Reader in = new InputStreamReader(new ByteArrayInputStream(input))) {
Object pemObject = new PEMParser(in).readObject();
if (pemObject instanceof SubjectPublicKeyInfo) {
return new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo) pemObject);
}
}
// Fall back to DER-encoded SubjectPublicKeyInfo
try {
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(input));
if (publicKeyInfo != null) {
return new JcaPEMKeyConverter().getPublicKey(publicKeyInfo);
}
} catch (Exception e) {
throw new IOException("Could not parse public key: " + e.getMessage(), e);
}
return null;
}
// d2i_RSAPrivateKey_bio
public static KeyPair readRSAPrivateKey(final byte[] input)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
return readRSAPrivateKey(SecurityHelper.getKeyFactory("RSA"), input);
}
public static KeyPair readRSAPrivateKey(final KeyFactory rsaFactory, final byte[] input)
throws IOException, InvalidKeySpecException {
ASN1Sequence seq;
ASN1Primitive obj = new ASN1InputStream(input).readObject();
if (obj instanceof ASN1Sequence && (seq = (ASN1Sequence) obj).size() == 9) {
BigInteger mod = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger pubexp = ((ASN1Integer) seq.getObjectAt(2)).getValue();
BigInteger privexp = ((ASN1Integer) seq.getObjectAt(3)).getValue();
BigInteger primep = ((ASN1Integer) seq.getObjectAt(4)).getValue();
BigInteger primeq = ((ASN1Integer) seq.getObjectAt(5)).getValue();
BigInteger primeep = ((ASN1Integer) seq.getObjectAt(6)).getValue();
BigInteger primeeq = ((ASN1Integer) seq.getObjectAt(7)).getValue();
BigInteger crtcoeff = ((ASN1Integer) seq.getObjectAt(8)).getValue();
PrivateKey priv = rsaFactory.generatePrivate(new RSAPrivateCrtKeySpec(mod, pubexp, privexp, primep, primeq, primeep, primeeq, crtcoeff));
PublicKey pub = rsaFactory.generatePublic(new RSAPublicKeySpec(mod, pubexp));
return new KeyPair(pub, priv);
}
return null;
}
// d2i_RSAPublicKey_bio
public static PublicKey readRSAPublicKey(final byte[] input)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
return readRSAPublicKey(SecurityHelper.getKeyFactory("RSA"), input);
}
public static PublicKey readRSAPublicKey(final KeyFactory rsaFactory, final byte[] input)
throws IOException, InvalidKeySpecException {
ASN1Sequence seq;
ASN1Primitive obj = new ASN1InputStream(input).readObject();
if (obj instanceof ASN1Sequence && (seq = (ASN1Sequence) obj).size() == 2) {
BigInteger mod = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger pubexp = ((ASN1Integer) seq.getObjectAt(1)).getValue();
return rsaFactory.generatePublic(new RSAPublicKeySpec(mod, pubexp));
}
return null;
}
// d2i_DSAPrivateKey_bio
public static KeyPair readDSAPrivateKey(final byte[] input)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
return readDSAPrivateKey(SecurityHelper.getKeyFactory("DSA"), input);
}
public static KeyPair readDSAPrivateKey(final KeyFactory dsaFactory, final byte[] input)
throws IOException, InvalidKeySpecException {
ASN1Sequence seq;
ASN1Primitive obj = new ASN1InputStream(input).readObject();
if (obj instanceof ASN1Sequence && (seq = (ASN1Sequence) obj).size() == 6) {
BigInteger p = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger q = ((ASN1Integer) seq.getObjectAt(2)).getValue();
BigInteger g = ((ASN1Integer) seq.getObjectAt(3)).getValue();
BigInteger y = ((ASN1Integer) seq.getObjectAt(4)).getValue();
BigInteger x = ((ASN1Integer) seq.getObjectAt(5)).getValue();
PrivateKey priv = dsaFactory.generatePrivate(new DSAPrivateKeySpec(x, p, q, g));
PublicKey pub = dsaFactory.generatePublic(new DSAPublicKeySpec(y, p, q, g));
return new KeyPair(pub, priv);
}
return null;
}
// d2i_DSA_PUBKEY_bio
public static PublicKey readDSAPublicKey(final byte[] input)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
return readDSAPublicKey(SecurityHelper.getKeyFactory("DSA"), input);
}
public static PublicKey readDSAPublicKey(final KeyFactory dsaFactory, final byte[] input)
throws IOException, InvalidKeySpecException {
ASN1Sequence seq;
ASN1Primitive obj = new ASN1InputStream(input).readObject();
if (obj instanceof ASN1Sequence) {
seq = (ASN1Sequence) obj;
if (seq.size() == 4) {
BigInteger y = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger p = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger q = ((ASN1Integer) seq.getObjectAt(2)).getValue();
BigInteger g = ((ASN1Integer) seq.getObjectAt(3)).getValue();
return dsaFactory.generatePublic(new DSAPublicKeySpec(y, p, q, g));
} else if (seq.size() == 2 && seq.getObjectAt(1) instanceof DERBitString) {
ASN1Integer y = (ASN1Integer)
new ASN1InputStream(((DERBitString) seq.getObjectAt(1)).getBytes()).readObject();
seq = (ASN1Sequence) ((ASN1Sequence) seq.getObjectAt(0)).getObjectAt(1);
BigInteger p = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger q = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger g = ((ASN1Integer) seq.getObjectAt(2)).getValue();
return dsaFactory.generatePublic(new DSAPublicKeySpec(y.getPositiveValue(), p, q, g));
}
}
return null;
}
// d2i_DHparams_bio
public static DHParameterSpec readDHParameter(final byte[] input) throws IOException {
ASN1InputStream aIn = new ASN1InputStream(input);
ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
BigInteger p = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger g = ((ASN1Integer) seq.getObjectAt(1)).getValue();
return new DHParameterSpec(p, g);
}
public static KeyPair readECPrivateKey(final byte[] input)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
return readECPrivateKey(SecurityHelper.getKeyFactory("EC"), input);
}
public static KeyPair readECPrivateKey(final KeyFactory keyFactory, final byte[] input)
throws IOException, InvalidKeySpecException {
return readECPrivateKey(keyFactory, mockPrivateKeyInfo(Type.EC, input));
}
public static KeyPair readECPrivateKey(final KeyFactory keyFactory, final PrivateKeyInfo keyInfo)
throws IOException, InvalidKeySpecException {
try {
ASN1Sequence seq = ASN1Sequence.getInstance(keyInfo.parsePrivateKey());
org.bouncycastle.asn1.sec.ECPrivateKey key = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
AlgorithmIdentifier algId = keyInfo.getPrivateKeyAlgorithm();
if (algId == null) { // mockPrivateKeyInfo
algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, key.getParametersObject().toASN1Primitive());
}
final PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, key);
ECPrivateKey privateKey = (ECPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privInfo.getEncoded()));
if (algId.getParameters() instanceof ASN1ObjectIdentifier) {
privateKey = ECPrivateKeyWithName.wrap(privateKey, (ASN1ObjectIdentifier) algId.getParameters());
}
// The publicKey field in ECPrivateKey DER is optional (RFC 5915).
// Keys written by older JRuby-OpenSSL may omit it; handle gracefully.
final org.bouncycastle.asn1.ASN1BitString pubKeyBits = key.getPublicKey();
if (pubKeyBits == null) return new KeyPair(null, privateKey);
final SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKeyBits.getBytes());
return new KeyPair(keyFactory.generatePublic(new X509EncodedKeySpec(pubInfo.getEncoded())), privateKey);
}
catch (ClassCastException ex) {
throw new IOException("wrong ASN.1 object found in stream", ex);
}
//catch (Exception ex) {
// throw new IOException("problem parsing EC private key: " + ex);
//}
}
public static byte[] toDerRSAKey(RSAPublicKey pubKey, RSAPrivateCrtKey privKey) throws IOException {
if ( pubKey != null && privKey == null ) {
return toDerRSAPublicKey(pubKey);
}
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(new ASN1Integer(BigInteger.ZERO));
vec.add(new ASN1Integer(privKey.getModulus()));
vec.add(new ASN1Integer(privKey.getPublicExponent()));
vec.add(new ASN1Integer(privKey.getPrivateExponent()));
vec.add(new ASN1Integer(privKey.getPrimeP()));
vec.add(new ASN1Integer(privKey.getPrimeQ()));
vec.add(new ASN1Integer(privKey.getPrimeExponentP()));
vec.add(new ASN1Integer(privKey.getPrimeExponentQ()));
vec.add(new ASN1Integer(privKey.getCrtCoefficient()));
return new DERSequence(vec).toASN1Primitive().getEncoded(ASN1Encoding.DER);
}
public static byte[] toDerRSAPublicKey(final RSAPublicKey pubKey) throws IOException {
// pubKey.getEncoded() :
return KeyUtil.getEncodedSubjectPublicKeyInfo(
new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), toASN1Primitive(pubKey)
);
}
public static ASN1Sequence toASN1Primitive(final RSAPublicKey publicKey) {
assert publicKey != null : "null public key";
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(new ASN1Integer(publicKey.getModulus()));
vec.add(new ASN1Integer(publicKey.getPublicExponent()));
return new DERSequence(vec);
}
public static byte[] toDerDSAKey(DSAPublicKey pubKey, DSAPrivateKey privKey)
throws IOException, IllegalArgumentException {
if ( pubKey != null && privKey == null ) {
return toDerDSAPublicKey(pubKey);
}
if ( privKey != null && pubKey != null ) {
ASN1EncodableVector vec = new ASN1EncodableVector();
final DSAParams params = privKey.getParams();
vec.add(new ASN1Integer(BigInteger.ZERO));
vec.add(new ASN1Integer(params.getP()));
vec.add(new ASN1Integer(params.getQ()));
vec.add(new ASN1Integer(params.getG()));
vec.add(new ASN1Integer(pubKey.getY()));
vec.add(new ASN1Integer(privKey.getX()));
return new DERSequence(vec).toASN1Primitive().getEncoded(ASN1Encoding.DER);
}
if ( privKey == null ) {
throw new IllegalArgumentException("private key as well as public key are null");
}
final DSAParams params = privKey.getParams();
return new PrivateKeyInfo(
new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa,
new DSAParameter(params.getP(), params.getQ(), params.getG())),
new ASN1Integer(privKey.getX())
).getEncoded(ASN1Encoding.DER);
}
public static byte[] toDerDSAPublicKey(final DSAPublicKey pubKey) throws IOException {
// pubKey.getEncoded() :
final DSAParams params = pubKey.getParams();
if (params == null) {
return new SubjectPublicKeyInfo(
new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa),
toASN1Primitive(pubKey)
).getEncoded(ASN1Encoding.DER);
}
return new SubjectPublicKeyInfo(
new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa,
new DSAParameter(params.getP(), params.getQ(), params.getG())
),
toASN1Primitive(pubKey)
).getEncoded(ASN1Encoding.DER);
}
public static ASN1Primitive toASN1Primitive(DSAPublicKey pubKey) {
return new ASN1Integer(pubKey.getY());
}
public static byte[] toDerDHKey(BigInteger p, BigInteger g) throws IOException {
ASN1EncodableVector vec = new ASN1EncodableVector();
if ( p != null ) vec.add( new ASN1Integer(p) );
if ( g != null ) vec.add( new ASN1Integer(g) );
return new DLSequence(vec).getEncoded();
}
}