-
Notifications
You must be signed in to change notification settings - Fork 79
/
PKeyEC.java
1015 lines (860 loc) · 38.6 KB
/
PKeyEC.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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2016 Karol Bucek.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jruby.ext.openssl;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.EllipticCurve;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import javax.crypto.KeyAgreement;
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.ASN1OutputStream;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.ECPointUtil;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.ext.openssl.impl.CipherSpec;
import static org.jruby.ext.openssl.OpenSSL.debug;
import static org.jruby.ext.openssl.OpenSSL.debugStackTrace;
import org.jruby.ext.openssl.impl.ECPrivateKeyWithName;
import static org.jruby.ext.openssl.impl.PKey.readECPrivateKey;
import org.jruby.ext.openssl.util.ByteArrayOutputStream;
import org.jruby.ext.openssl.x509store.PEMInputOutput;
/**
* OpenSSL::PKey::EC implementation.
*
* @author kares
*/
public final class PKeyEC extends PKey {
private static final long serialVersionUID = 1L;
private static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public PKeyEC allocate(Ruby runtime, RubyClass klass) { return new PKeyEC(runtime, klass); }
};
static PKeyEC newInstance(final Ruby runtime, final PublicKey publicKey) {
return new PKeyEC(runtime, publicKey);
}
static void createPKeyEC(final Ruby runtime, final RubyModule PKey, final RubyClass PKeyPKey, final RubyClass OpenSSLError) {
RubyClass EC = PKey.defineClassUnder("EC", PKeyPKey, ALLOCATOR);
RubyClass PKeyError = PKey.getClass("PKeyError");
PKey.defineClassUnder("ECError", PKeyError, PKeyError.getAllocator());
EC.defineAnnotatedMethods(PKeyEC.class);
EC.setConstant("NAMED_CURVE", runtime.newFixnum(1));
Point.createPoint(runtime, EC, OpenSSLError);
Group.createGroup(runtime, EC, OpenSSLError);
}
static RubyClass _EC(final Ruby runtime) {
return _PKey(runtime).getClass("EC");
}
private static RaiseException newECError(Ruby runtime, String message) {
return Utils.newError(runtime, _PKey(runtime).getClass("ECError"), message);
}
private static RaiseException newECError(Ruby runtime, String message, Exception cause) {
return Utils.newError(runtime, _PKey(runtime).getClass("ECError"), message, cause);
}
@JRubyMethod(meta = true)
public static RubyArray builtin_curves(ThreadContext context, IRubyObject self) {
final Ruby runtime = context.runtime;
final RubyArray curves = runtime.newArray();
Enumeration names;
names = org.bouncycastle.asn1.x9.X962NamedCurves.getNames();
while ( names.hasMoreElements() ) {
final String name = (String) names.nextElement();
RubyString desc;
if ( name.startsWith("prime") ) {
desc = RubyString.newString(runtime, "X9.62 curve over a xxx bit prime field");
}
else {
desc = RubyString.newString(runtime, "X9.62 curve over a xxx bit binary field");
}
curves.append(RubyArray.newArrayNoCopy(runtime, new IRubyObject[] { RubyString.newString(runtime, name), desc }));
}
names = org.bouncycastle.asn1.sec.SECNamedCurves.getNames();
while ( names.hasMoreElements() ) {
RubyString name = RubyString.newString(runtime, (String) names.nextElement());
RubyString desc = RubyString.newString(runtime, "SECG curve over a xxx bit binary field");
curves.append(RubyArray.newArrayNoCopy(runtime, new IRubyObject[] { name, desc }));
}
names = org.bouncycastle.asn1.nist.NISTNamedCurves.getNames();
while ( names.hasMoreElements() ) {
RubyString name = RubyString.newString(runtime, (String) names.nextElement());
IRubyObject[] nameAndDesc = new IRubyObject[] { name, RubyString.newEmptyString(runtime) };
curves.append(RubyArray.newArrayNoCopy(runtime, nameAndDesc));
}
names = org.bouncycastle.asn1.teletrust.TeleTrusTNamedCurves.getNames();
while ( names.hasMoreElements() ) {
RubyString name = RubyString.newString(runtime, (String) names.nextElement());
RubyString desc = RubyString.newString(runtime, "RFC 5639 curve over a xxx bit prime field");
curves.append(RubyArray.newArrayNoCopy(runtime, new IRubyObject[] { name, desc }));
}
return curves;
}
private static Optional<ASN1ObjectIdentifier> getCurveOID(final String curveName) {
ASN1ObjectIdentifier id;
id = org.bouncycastle.asn1.sec.SECNamedCurves.getOID(curveName);
if ( id != null ) return Optional.of(id);
id = org.bouncycastle.asn1.x9.X962NamedCurves.getOID(curveName);
if ( id != null ) return Optional.of(id);
id = org.bouncycastle.asn1.nist.NISTNamedCurves.getOID(curveName);
if ( id != null ) return Optional.of(id);
id = org.bouncycastle.asn1.teletrust.TeleTrusTNamedCurves.getOID(curveName);
if ( id != null ) return Optional.of(id);
return Optional.empty();
}
private static boolean isCurveName(final String curveName) {
return getCurveOID(curveName).isPresent();
}
private static String getCurveName(final ASN1ObjectIdentifier oid) {
String name;
name = org.bouncycastle.asn1.sec.SECNamedCurves.getName(oid);
if ( name != null ) return name;
name = org.bouncycastle.asn1.x9.X962NamedCurves.getName(oid);
if ( name != null ) return name;
name = org.bouncycastle.asn1.nist.NISTNamedCurves.getName(oid);
if ( name != null ) return name;
name = org.bouncycastle.asn1.teletrust.TeleTrusTNamedCurves.getName(oid);
if ( name != null ) return name;
throw new IllegalStateException("could not identify curve name from: " + oid);
}
public PKeyEC(Ruby runtime, RubyClass type) {
super(runtime, type);
}
PKeyEC(Ruby runtime, PublicKey pubKey) {
this(runtime, _EC(runtime), null, pubKey);
}
PKeyEC(Ruby runtime, RubyClass type, PrivateKey privKey, PublicKey pubKey) {
super(runtime, type);
this.publicKey = (ECPublicKey) pubKey;
if (privKey instanceof ECPrivateKey) {
setPrivateKey((ECPrivateKey) privKey);
} else {
this.privateKey = privKey;
}
}
private transient Group group;
private ECPublicKey publicKey;
private transient PrivateKey privateKey;
private String curveName;
private String getCurveName() { return curveName; }
private ECNamedCurveParameterSpec getParameterSpec() {
assert curveName != null;
return ECNamedCurveTable.getParameterSpec(getCurveName());
}
@Override
public PublicKey getPublicKey() { return publicKey; }
@Override
public PrivateKey getPrivateKey() { return privateKey; }
@Override
public String getAlgorithm() { return "ECDSA"; }
@Override
public String getKeyType() { return "EC"; }
@JRubyMethod(rest = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(final ThreadContext context, final IRubyObject[] args, Block block) {
final Ruby runtime = context.runtime;
privateKey = null; publicKey = null;
if ( Arity.checkArgumentCount(runtime, args, 0, 2) == 0 ) {
return this;
}
IRubyObject arg = args[0];
if ( arg instanceof Group ) {
setGroup((Group) arg);
return this;
}
IRubyObject pass = null;
if ( args.length > 1 ) pass = args[1];
final char[] passwd = password(context, pass, block);
final RubyString str = readInitArg(context, arg);
final String strJava = str.toString();
if ( isCurveName(strJava) ) {
this.curveName = strJava;
return this;
}
Object key = null;
final KeyFactory ecdsaFactory;
try {
ecdsaFactory = SecurityHelper.getKeyFactory("EC");
}
catch (NoSuchAlgorithmException e) {
throw runtime.newRuntimeError("unsupported key algorithm (EC)");
}
catch (RuntimeException e) {
throw runtime.newRuntimeError("unsupported key algorithm (EC) " + e);
}
// TODO: ugly NoClassDefFoundError catching for no BC env. How can we remove this?
boolean noClassDef = false;
if ( key == null && ! noClassDef ) { // PEM_read_bio_DSAPrivateKey
try {
key = readPrivateKey(strJava, passwd);
}
catch (NoClassDefFoundError e) { noClassDef = true; debugStackTrace(runtime, e); }
catch (PEMInputOutput.PasswordRequiredException retry) {
if ( ttySTDIN(context) ) {
try { key = readPrivateKey(str, passwordPrompt(context)); }
catch (Exception e) { debugStackTrace(runtime, e); }
}
}
catch (Exception e) { debugStackTrace(runtime, e); }
}
if ( key == null && ! noClassDef ) {
try {
key = PEMInputOutput.readECPublicKey(new StringReader(strJava), passwd);
}
catch (NoClassDefFoundError e) { noClassDef = true; debugStackTrace(runtime, e); }
catch (Exception e) { debugStackTrace(runtime, e); }
}
if ( key == null && ! noClassDef ) {
try {
key = PEMInputOutput.readECPubKey(new StringReader(strJava));
}
catch (NoClassDefFoundError e) { noClassDef = true; debugStackTrace(runtime, e); }
catch (Exception e) { debugStackTrace(runtime, e); }
}
if ( key == null && ! noClassDef ) {
try {
key = readECPrivateKey(ecdsaFactory, str.getBytes());
}
catch (NoClassDefFoundError e) { noClassDef = true; debugStackTrace(runtime, e); }
catch (InvalidKeySpecException e) { debug(runtime, "PKeyEC could not read private key", e); }
catch (IOException e) { debugStackTrace(runtime, "PKeyEC could not read private key", e); }
catch (RuntimeException e) {
if ( isKeyGenerationFailure(e) ) debug(runtime, "PKeyEC could not read private key", e);
else debugStackTrace(runtime, e);
}
}
// if ( key == null && ! noClassDef ) {
// try { // readECParameters
// ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(str.getBytes());
// ECNamedCurveParameterSpec paramSpec = ECNamedCurveTable.getParameterSpec(oid.getId());
//
// // ecdsaFactory.generatePublic(keySpec)
//
// }
// catch (NoClassDefFoundError e) { noClassDef = true; debugStackTrace(runtime, e); }
// catch (InvalidKeySpecException e) { debug(runtime, "PKeyEC could not read public key", e); }
// catch (IOException e) { debug(runtime, "PKeyEC could not read public key", e); }
// catch (RuntimeException e) {
// if ( isKeyGenerationFailure(e) ) debug(runtime, "PKeyEC could not read public key", e);
// else debugStackTrace(runtime, e);
// }
// }
if ( key == null ) key = tryPKCS8EncodedKey(runtime, ecdsaFactory, str.getBytes());
if ( key == null ) key = tryX509EncodedKey(runtime, ecdsaFactory, str.getBytes());
if ( key == null ) throw newECError(runtime, "Neither PUB key nor PRIV key:");
if ( key instanceof KeyPair ) {
final PublicKey pubKey = ((KeyPair) key).getPublic();
final PrivateKey privKey = ((KeyPair) key).getPrivate();
if ( ! ( privKey instanceof ECPrivateKey ) ) {
if ( privKey == null ) {
throw newECError(runtime, "Neither PUB key nor PRIV key: (private key is null)");
}
throw newECError(runtime, "Neither PUB key nor PRIV key: (invalid key type " + privKey.getClass().getName() + ")");
}
this.publicKey = (ECPublicKey) pubKey;
setPrivateKey((ECPrivateKey) privKey);
}
else if ( key instanceof ECPrivateKey ) {
setPrivateKey((ECPrivateKey) key);
}
else if ( key instanceof ECPublicKey ) {
this.publicKey = (ECPublicKey) key;
this.privateKey = null;
}
else {
throw newECError(runtime, "Neither PUB key nor PRIV key: " + key.getClass().getName());
}
if ( curveName == null && publicKey != null ) {
final String oid = getCurveNameObjectIdFromKey(context, publicKey);
if (isCurveName(oid)) {
this.curveName = getCurveName(new ASN1ObjectIdentifier(oid));
}
}
return this;
}
void setPrivateKey(final ECPrivateKey key) {
this.privateKey = key;
unwrapPrivateKeyWithName();
}
private void unwrapPrivateKeyWithName() {
final ECPrivateKey privKey = (ECPrivateKey) this.privateKey;
if ( privKey instanceof ECPrivateKeyWithName ) {
this.privateKey = ((ECPrivateKeyWithName) privKey).unwrap();
this.curveName = getCurveName( ((ECPrivateKeyWithName) privKey).getCurveNameOID() );
}
}
private static String getCurveNameObjectIdFromKey(final ThreadContext context, final ECPublicKey key) {
try {
AlgorithmParameters algParams = AlgorithmParameters.getInstance("EC");
algParams.init(key.getParams());
return algParams.getParameterSpec(ECGenParameterSpec.class).getName();
}
catch (NoSuchAlgorithmException|InvalidParameterSpecException ex) {
throw newECError(context.runtime, ex.getMessage());
}
catch (Exception ex) {
throw (RaiseException) newECError(context.runtime, ex.toString()).initCause(ex);
}
}
private void setGroup(final Group group) {
this.group = group;
this.curveName = this.group.getCurveName();
}
//private static ECNamedCurveParameterSpec readECParameters(final byte[] input) throws IOException {
// ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(input);
// return ECNamedCurveTable.getParameterSpec(oid.getId());
//}
@JRubyMethod
public IRubyObject check_key(final ThreadContext context) {
return context.runtime.getTrue(); // TODO not implemented stub
}
@JRubyMethod(name = "generate_key")
public PKeyEC generate_key(final ThreadContext context) {
try {
ECGenParameterSpec genSpec = new ECGenParameterSpec(getCurveName());
KeyPairGenerator gen = SecurityHelper.getKeyPairGenerator("EC"); // "BC"
gen.initialize(genSpec, OpenSSL.getSecureRandom(context));
KeyPair pair = gen.generateKeyPair();
this.publicKey = (ECPublicKey) pair.getPublic();
this.privateKey = pair.getPrivate();
}
catch (GeneralSecurityException ex) {
throw newECError(context.runtime, ex.toString());
}
return this;
}
@JRubyMethod(meta = true)
public static IRubyObject generate(final ThreadContext context, final IRubyObject self, final IRubyObject group) {
PKeyEC randomKey = new PKeyEC(context.runtime, (RubyClass) self);
if (group instanceof Group) {
randomKey.setGroup((Group) group);
} else {
randomKey.curveName = group.convertToString().toString();
}
return randomKey.generate_key(context);
}
@JRubyMethod(name = "dsa_sign_asn1")
public IRubyObject dsa_sign_asn1(final ThreadContext context, final IRubyObject data) {
if (privateKey == null) {
throw newECError(context.runtime, "Private EC key needed!");
}
try {
final ECNamedCurveParameterSpec params = getParameterSpec();
final ECDSASigner signer = new ECDSASigner();
signer.init(true, new ECPrivateKeyParameters(
((ECPrivateKey) this.privateKey).getS(),
new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH())
));
BigInteger[] signature = signer.generateSignature(data.convertToString().getBytes()); // [r, s]
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ASN1OutputStream asn1 = ASN1OutputStream.create(bytes, ASN1Encoding.DER);
ASN1EncodableVector v = new ASN1EncodableVector(2);
v.add(new ASN1Integer(signature[0])); // r
v.add(new ASN1Integer(signature[1])); // s
asn1.writeObject(new DERSequence(v));
asn1.close();
return StringHelper.newString(context.runtime, bytes.buffer(), bytes.size());
}
catch (IOException ex) {
throw newECError(context.runtime, ex.getMessage());
}
catch (Exception ex) {
throw newECError(context.runtime, ex.toString(), ex);
}
}
@JRubyMethod(name = "dsa_verify_asn1")
public IRubyObject dsa_verify_asn1(final ThreadContext context, final IRubyObject data, final IRubyObject sign) {
final Ruby runtime = context.runtime;
try {
final ECNamedCurveParameterSpec params = getParameterSpec();
final ECDSASigner signer = new ECDSASigner();
signer.init(false, new ECPublicKeyParameters(
EC5Util.convertPoint(publicKey.getParams(), publicKey.getW()),
new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH())
));
ASN1Primitive vec = new ASN1InputStream(sign.convertToString().getBytes()).readObject();
if (!(vec instanceof ASN1Sequence)) {
throw newECError(runtime, "invalid signature (not a sequence)");
}
ASN1Sequence seq = (ASN1Sequence) vec;
ASN1Integer r = ASN1Integer.getInstance(seq.getObjectAt(0));
ASN1Integer s = ASN1Integer.getInstance(seq.getObjectAt(1));
boolean verify = signer.verifySignature(data.convertToString().getBytes(), r.getPositiveValue(), s.getPositiveValue());
return runtime.newBoolean(verify);
}
catch (IOException|IllegalArgumentException|IllegalStateException ex) {
throw newECError(runtime, "invalid signature: " + ex.getMessage(), ex);
}
}
@JRubyMethod(name = "dh_compute_key")
public IRubyObject dh_compute_key(final ThreadContext context, final IRubyObject point) {
try {
KeyAgreement agreement = SecurityHelper.getKeyAgreement("ECDH"); // "BC"
agreement.init(getPrivateKey());
if ( point.isNil() ) {
agreement.doPhase(getPublicKey(), true);
}
else {
final ECPoint ecPoint = ((Point) point).asECPoint();
final String name = getCurveName();
KeyFactory keyFactory = KeyFactory.getInstance("EC"); // "BC"
ECParameterSpec spec = getParamSpec(name);
ECPublicKey ecPublicKey = (ECPublicKey) keyFactory.generatePublic(new ECPublicKeySpec(ecPoint, spec));
agreement.doPhase(ecPublicKey, true);
}
final byte[] secret = agreement.generateSecret();
return StringHelper.newString(context.runtime, secret);
}
catch (InvalidKeyException ex) {
throw newECError(context.runtime, "invalid key: " + ex.getMessage());
}
catch (GeneralSecurityException ex) {
throw newECError(context.runtime, ex.toString());
}
}
private Group getGroup(boolean required) {
if (group == null) {
if (publicKey != null) {
return group = new Group(getRuntime(), this);
}
if (required) throw new IllegalStateException("no group (without public key)");
}
return group;
}
/**
* @return OpenSSL::PKey::EC::Group
*/
@JRubyMethod
public IRubyObject group() {
final Group group = getGroup(false);
return group == null ? getRuntime().getNil() : group;
}
@JRubyMethod(name = "group=")
public IRubyObject set_group(IRubyObject group) {
this.group = group.isNil() ? null : (Group) group;
return group;
}
/**
* @return OpenSSL::PKey::EC::Point
*/
@JRubyMethod
public IRubyObject public_key(final ThreadContext context) {
if ( publicKey == null ) return context.nil;
return new Point(context.runtime, publicKey, getGroup(true));
}
@JRubyMethod(name = "public_key=")
public IRubyObject set_public_key(final ThreadContext context, final IRubyObject arg) {
if ( ! ( arg instanceof Point ) ) {
throw context.runtime.newTypeError(arg, _EC(context.runtime).getClass("Point"));
}
final Point point = (Point) arg;
ECPublicKeySpec keySpec = new ECPublicKeySpec(point.asECPoint(), getParamSpec());
try {
this.publicKey = (ECPublicKey) SecurityHelper.getKeyFactory("EC").generatePublic(keySpec);
return arg;
}
catch (GeneralSecurityException ex) {
throw newECError(context.runtime, ex.getMessage());
}
}
private static ECParameterSpec getParamSpec(final String curveName) {
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName);
return new ECNamedCurveSpec(spec.getName(), spec.getCurve(), spec.getG(), spec.getN(), spec.getH(), spec.getSeed());
}
private ECParameterSpec getParamSpec() {
return getParamSpec(getCurveName());
}
/**
* @return OpenSSL::BN
*/
@JRubyMethod
public IRubyObject private_key(final ThreadContext context) {
if ( privateKey == null ) return context.nil;
return BN.newBN(context.runtime, ((ECPrivateKey) privateKey).getS());
}
@JRubyMethod(name = "private_key=")
public IRubyObject set_private_key(final ThreadContext context, final IRubyObject arg) {
final BigInteger s;
if ( arg instanceof BN ) {
s = ((BN) (arg)).getValue();
}
else {
s = (BigInteger) arg;
}
ECPrivateKeySpec keySpec = new ECPrivateKeySpec(s, getParamSpec());
try {
this.privateKey = SecurityHelper.getKeyFactory("EC").generatePrivate(keySpec);
return arg;
}
catch (GeneralSecurityException ex) {
throw newECError(context.runtime, ex.getMessage());
}
}
@JRubyMethod(name = "public_key?")
public RubyBoolean public_p() {
return publicKey != null ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "private_key?")
public RubyBoolean private_p() {
return privateKey != null ? getRuntime().getTrue() : getRuntime().getFalse();
}
@Override
@JRubyMethod(name = "to_der")
public RubyString to_der() {
final byte[] bytes;
try {
bytes = toDER();
}
catch (IOException e) {
throw newECError(getRuntime(), e.getMessage());
}
return StringHelper.newString(getRuntime(), bytes);
}
private byte[] toDER() throws IOException {
if ( publicKey != null && privateKey == null ) {
return publicKey.getEncoded();
}
if ( privateKey == null ) {
throw new IllegalStateException("private key as well as public key are null");
}
return privateKey.getEncoded();
}
@Override
@JRubyMethod(name = "to_pem", alias = "export", rest = true)
public RubyString to_pem(ThreadContext context, final IRubyObject[] args) {
Arity.checkArgumentCount(context.runtime, args, 0, 2);
CipherSpec spec = null; char[] passwd = null;
if ( args.length > 0 ) {
spec = cipherSpec( args[0] );
if ( args.length > 1 ) passwd = password(context, args[1], null);
}
try {
final StringWriter writer = new StringWriter();
if ( privateKey != null ) {
PEMInputOutput.writeECPrivateKey(writer, (ECPrivateKey) privateKey, spec, passwd);
}
else {
PEMInputOutput.writeECPublicKey(writer, publicKey);
}
return RubyString.newString(context.runtime, writer.getBuffer());
}
catch (IOException ex) {
throw newECError(context.runtime, ex.getMessage());
}
}
@JRubyClass(name = "OpenSSL::PKey::EC::Group")
public static final class Group extends RubyObject {
private static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public Group allocate(Ruby runtime, RubyClass klass) { return new Group(runtime, klass); }
};
static void createGroup(final Ruby runtime, final RubyClass EC, final RubyClass OpenSSLError) {
RubyClass Group = EC.defineClassUnder("Group", runtime.getObject(), ALLOCATOR);
// OpenSSL::PKey::EC::Group::Error
Group.defineClassUnder("Error", OpenSSLError, OpenSSLError.getAllocator());
Group.defineAnnotatedMethods(Group.class);
}
private transient PKeyEC key;
private ECParameterSpec paramSpec;
private RubyString curve_name;
public Group(Ruby runtime, RubyClass type) {
super(runtime, type);
}
Group(Ruby runtime, PKeyEC key) {
this(runtime, _EC(runtime).getClass("Group"));
this.key = key;
this.paramSpec = key.publicKey.getParams();
}
private String getCurveName() {
if (key != null) return key.getCurveName();
return curve_name.toString();
}
@JRubyMethod(rest = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(final ThreadContext context, final IRubyObject[] args) {
final Ruby runtime = context.runtime;
if ( Arity.checkArgumentCount(runtime, args, 1, 4) == 1 ) {
IRubyObject arg = args[0];
if ( arg instanceof Group ) {
IRubyObject curve_name = ((Group) arg).curve_name(context);
this.curve_name = curve_name.isNil() ? null : (RubyString) curve_name;
return this;
}
this.curve_name = ((RubyString) arg);
// TODO PEM/DER parsing not implemented
}
return this;
}
@Override
@JRubyMethod(name = { "==", "eql?" })
public IRubyObject op_equal(final ThreadContext context, final IRubyObject obj) {
if ( paramSpec == null ) return context.nil;
if ( obj instanceof Group ) {
final Group that = (Group) obj;
boolean equals = this.paramSpec.equals(that.paramSpec);
return context.runtime.newBoolean(equals);
}
return context.runtime.getFalse();
}
@JRubyMethod
public IRubyObject curve_name(final ThreadContext context) {
if (curve_name == null) {
String prefix, curveName = key.getCurveName();
// BC 1.54: "brainpoolP512t1" 1.55: "brainpoolp512t1"
if (curveName.startsWith(prefix = "brainpoolp")) {
curveName = "brainpoolP" + curveName.substring(prefix.length());
}
curve_name = RubyString.newString(context.runtime, curveName);
}
return curve_name.dup();
}
@JRubyMethod
public IRubyObject order(final ThreadContext context) {
if ( paramSpec == null ) return context.nil;
return BN.newBN(context.runtime, paramSpec.getOrder());
}
@JRubyMethod
public IRubyObject cofactor(final ThreadContext context) {
if ( paramSpec == null ) return context.nil;
return context.runtime.newFixnum(paramSpec.getCofactor());
}
@JRubyMethod
public IRubyObject seed(final ThreadContext context) {
if ( paramSpec == null ) return context.nil;
final byte[] seed = paramSpec.getCurve().getSeed();
return seed == null ? context.nil : StringHelper.newString(context.runtime, seed);
}
@JRubyMethod
public IRubyObject degree(final ThreadContext context) {
if ( paramSpec == null ) return context.nil;
final int fieldSize = paramSpec.getCurve().getField().getFieldSize();
return context.runtime.newFixnum(fieldSize);
}
@JRubyMethod
public IRubyObject generator(final ThreadContext context) {
if ( paramSpec == null ) return context.nil;
final ECPoint generator = paramSpec.getGenerator();
//final int bitLength = paramSpec.getOrder().bitLength();
return new Point(context.runtime, generator, this);
}
@JRubyMethod(name = { "to_pem" }, alias = "export", rest = true)
public RubyString to_pem(final ThreadContext context, final IRubyObject[] args) {
Arity.checkArgumentCount(context.runtime, args, 0, 2);
CipherSpec spec = null; char[] passwd = null;
if ( args.length > 0 ) {
spec = cipherSpec( args[0] );
if ( args.length > 1 ) passwd = password(context, args[1], null);
}
try {
final StringWriter writer = new StringWriter();
final ASN1ObjectIdentifier oid = getCurveOID(getCurveName())
.orElseThrow(() -> newECError(context.runtime, "invalid curve name: " + getCurveName()));
PEMInputOutput.writeECParameters(writer, oid, spec, passwd);
return RubyString.newString(context.runtime, writer.getBuffer());
}
catch (IOException ex) {
throw newECError(context.runtime, ex.getMessage());
}
}
final EllipticCurve getCurve() {
if (paramSpec == null) {
paramSpec = getParamSpec(getCurveName());
}
return paramSpec.getCurve();
}
// @Override
// @JRubyMethod
// @SuppressWarnings("unchecked")
// public IRubyObject inspect() {
// final EllipticCurve curve = getCurve();
// final StringBuilder part = new StringBuilder();
// String cname = getMetaClass().getRealClass().getName();
// part.append("#<").append(cname).append(":0x");
// part.append(Integer.toHexString(System.identityHashCode(this)));
// // part.append(' ');
// part.append(" a:").append(curve.getA()).append(" b:").append(curve.getA());
// return RubyString.newString(getRuntime(), part.append('>'));
// }
}
@JRubyClass(name = "OpenSSL::PKey::EC::Point")
public static final class Point extends RubyObject {
private static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public Point allocate(Ruby runtime, RubyClass klass) { return new Point(runtime, klass); }
};
static void createPoint(final Ruby runtime, final RubyClass EC, final RubyClass OpenSSLError) {
RubyClass Point = EC.defineClassUnder("Point", runtime.getObject(), ALLOCATOR);
// OpenSSL::PKey::EC::Point::Error
Point.defineClassUnder("Error", OpenSSLError, OpenSSLError.getAllocator());
Point.defineAnnotatedMethods(Point.class);
}
public Point(Ruby runtime, RubyClass type) {
super(runtime, type);
}
// private transient ECPublicKey publicKey;
private ECPoint point;
//private int bitLength;
private Group group;
Point(Ruby runtime, ECPublicKey publicKey, Group group) {
this(runtime, _EC(runtime).getClass("Point"));
//this.publicKey = publicKey;
this.point = publicKey.getW();
this.group = group;
}
Point(Ruby runtime, ECPoint point, Group group) {
this(runtime, _EC(runtime).getClass("Point"));
this.point = point;
this.group = group;
}
private static RaiseException newError(final Ruby runtime, final String message) {
final RubyClass Error = _EC(runtime).getClass("Point").getClass("Error");
return Utils.newError(runtime, Error, message);
}
@JRubyMethod(rest = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(final ThreadContext context, final IRubyObject[] args) {
final Ruby runtime = context.runtime;
final int argc = Arity.checkArgumentCount(runtime, args, 1, 2);
final IRubyObject arg = args[0];
if ( arg instanceof Point ) {
this.group = ((Point) arg).group;
this.point = ((Point) arg).point;
return this;
}
if ( arg instanceof Group ) {
this.group = (Group) arg;
}
if ( argc == 2 ) { // (group, bn)
final byte[] encoded = ((BN) args[1]).getValue().abs().toByteArray();
try {
this.point = ECPointUtil.decodePoint(group.getCurve(), encoded);
}
catch (IllegalArgumentException ex) {
// MRI: OpenSSL::PKey::EC::Point::Error: invalid encoding
throw newError(context.runtime, ex.getMessage());
}
}
return this;
}
@Override
@JRubyMethod(name = { "==", "eql?" })
public IRubyObject op_equal(final ThreadContext context, final IRubyObject obj) {
if (obj instanceof Point) {
final Point that = (Point) obj;
boolean equals = this.point.equals(that.point);
return context.runtime.newBoolean(equals);
}
return context.runtime.getFalse();
}
/**
* @return OpenSSL::PKey::EC::Group
*/
@JRubyMethod
public IRubyObject group() {
return group == null ? getRuntime().getNil() : group;
}
private ECPoint asECPoint() {
return point; // return publicKey.getW();
}
private int bitLength() {
return group.paramSpec.getOrder().bitLength();
}
@JRubyMethod
public BN to_bn(final ThreadContext context) {
final byte[] encoded = encode(bitLength(), point);
return BN.newBN(context.runtime, new BigInteger(1, encoded));
}
private boolean isInfinity() {
return point == ECPoint.POINT_INFINITY;
}
@JRubyMethod(name = "infinity?")
public RubyBoolean infinity_p() {
return getRuntime().newBoolean( isInfinity() );
}
@JRubyMethod(name = "set_to_infinity!")
public IRubyObject set_to_infinity_b() {
this.point = ECPoint.POINT_INFINITY;
return this;
}
@Override
@JRubyMethod
@SuppressWarnings("unchecked")
public IRubyObject inspect() {
VariableEntry entry = new VariableEntry( "group", group == null ? (Object) "nil" : group );
return ObjectSupport.inspect(this, (List) Collections.singletonList(entry));
}
}
static byte[] encode(final ECPublicKey pubKey) {
return encode(pubKey.getParams().getOrder().bitLength(), pubKey.getW());
}
private static byte[] encode(final int bitLength, final ECPoint point) {
if ( point == ECPoint.POINT_INFINITY ) return new byte[1];
final int bytesLength = (bitLength + 7) / 8;
byte[] encoded = new byte[1 + bytesLength + bytesLength];
encoded[0] = 0x04;
addIntBytes(point.getAffineX(), bytesLength, encoded, 1);
addIntBytes(point.getAffineY(), bytesLength, encoded, 1 + bytesLength);
return encoded;
}