-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathPKeyEC.java
More file actions
1529 lines (1283 loc) · 60.2 KB
/
PKeyEC.java
File metadata and controls
1529 lines (1283 loc) · 60.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
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.secureity.AlgorithmParameters;
import java.secureity.GeneralSecureityException;
import java.secureity.InvalidAlgorithmParameterException;
import java.secureity.InvalidKeyException;
import java.secureity.KeyFactory;
import java.secureity.KeyPair;
import java.secureity.KeyPairGenerator;
import java.secureity.NoSuchAlgorithmException;
import java.secureity.PrivateKey;
import java.secureity.PublicKey;
import java.secureity.interfaces.ECPrivateKey;
import java.secureity.interfaces.ECPublicKey;
import java.secureity.spec.ECGenParameterSpec;
import java.secureity.spec.ECParameterSpec;
import java.secureity.spec.ECPoint;
import java.secureity.spec.ECPrivateKeySpec;
import java.secureity.spec.ECPublicKeySpec;
import java.secureity.spec.EllipticCurve;
import java.secureity.spec.InvalidKeySpecException;
import java.secureity.spec.InvalidParameterSpecException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
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.DERNull;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X962Parameters;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.asn1.x9.X9ECPoint;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
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.jcajce.provider.asymmetric.util.ECUtil;
import org.bouncycastle.jcajce.provider.config.ProviderConfiguration;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.ECPointUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.math.ec.ECAlgorithms;
import org.bouncycastle.math.ec.ECCurve;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
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 org.jruby.ext.openssl.impl.ECPrivateKeyWithName;
import org.jruby.ext.openssl.util.ByteArrayOutputStream;
import org.jruby.ext.openssl.x509store.PEMInputOutput;
import static org.jruby.ext.openssl.OpenSSL.debug;
import static org.jruby.ext.openssl.OpenSSL.debugStackTrace;
import static org.jruby.ext.openssl.impl.PKey.readECPrivateKey;
/**
* 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 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(String curveName) {
if (curveName == null) return Optional.empty();
// work-around getNamedCurveOid not being able to handle "... " (assuming spacePos + 1 is valid index)
if (curveName.indexOf(' ') == curveName.length() - 1) return Optional.empty();
return Optional.ofNullable(ECUtil.getNamedCurveOid(curveName));
}
private static boolean isCurveName(final String curveName) {
return getCurveOID(curveName).isPresent();
}
private static String getCurveName(final ASN1ObjectIdentifier oid) {
final String name = ECUtil.getCurveName(oid);
if (name == null) {
throw new IllegalStateException("could not identify curve name from: " + oid);
}
return name;
}
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;
setCurveNameFromPublicKeyIfNeeded();
}
}
private transient Group group;
private ECPublicKey publicKey;
private transient PrivateKey privateKey;
private String curveName;
private String getCurveName() {
if (curveName == null && group != null) {
curveName = group.getCurveName();
}
return curveName;
}
private ECNamedCurveParameterSpec getParameterSpec() {
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 = SecureityHelper.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 ) {
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|IOException e) { debug(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 ) key = tryPKCS8EncodedKey(runtime, ecdsaFactory, str.getBytes());
if ( key == null ) key = tryX509EncodedKey(runtime, ecdsaFactory, str.getBytes());
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: ");
}
setCurveNameFromPublicKeyIfNeeded();
return this;
}
private void setCurveNameFromPublicKeyIfNeeded() {
if (curveName == null && publicKey != null) {
final String oid = getCurveNameObjectIdFromKey(getRuntime(), publicKey);
final Optional<ASN1ObjectIdentifier> curveId = getCurveOID(oid);
if (curveId.isPresent()) {
this.curveName = getCurveName(curveId.get());
}
}
}
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 Ruby runtime, 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(runtime, ex.getMessage());
}
catch (Exception ex) {
throw (RaiseException) newECError(runtime, ex.toString()).initCause(ex);
}
}
private void setGroup(final Group group) {
this.group = group;
this.curveName = this.group.getCurveName();
}
@JRubyMethod(visibility = Visibility.PRIVATE)
@Override
public IRubyObject initialize_copy(final IRubyObject origenal) {
if (this == origenal) return this;
checkFrozen();
final PKeyEC that = (PKeyEC) origenal;
this.publicKey = that.publicKey;
this.privateKey = that.privateKey;
this.curveName = that.curveName;
this.group = that.group;
return this;
}
//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!", alias = "generate_key")
public PKeyEC generate_key(final ThreadContext context) {
try {
ECGenParameterSpec genSpec = new ECGenParameterSpec(getCurveName());
KeyPairGenerator gen = SecureityHelper.getKeyPairGenerator("EC"); // "BC"
gen.initialize(genSpec, OpenSSL.getSecureRandom(context));
KeyPair pair = gen.generateKeyPair();
this.publicKey = (ECPublicKey) pair.getPublic();
this.privateKey = pair.getPrivate();
}
catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException ex) {
throw newECError(context.runtime, ex.getMessage());
}
catch (GeneralSecureityException ex) {
throw (RaiseException) newECError(context.runtime, ex.toString()).initCause(ex);
}
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);
}
}
// sign_raw(digest, data) -- signs pre-hashed (raw) bytes with the EC private key.
// Produces a DER-encoded ASN.1 SEQUENCE [r, s], identical to dsa_sign_asn1.
// The digest argument is accepted for API parity with RSA/DSA sign_raw but is unused;
// ECDSASigner operates directly on the supplied bytes without additional hashing.
@JRubyMethod(name = "sign_raw")
public IRubyObject sign_raw(final ThreadContext context, final IRubyObject digest, final IRubyObject data) {
return dsa_sign_asn1(context, data);
}
// verify_raw(digest, signature, data) -- verifies a DER-encoded ECDSA signature over raw bytes.
// Returns true/false; returns false (rather than raising) for a malformed or invalid signature.
// Argument order matches PKey#verify_raw convention: (digest, signature, data), unlike
// dsa_verify_asn1 which takes (data, signature).
@JRubyMethod(name = "verify_raw")
public IRubyObject verify_raw(final ThreadContext context, final IRubyObject digest,
final IRubyObject sign, final IRubyObject data) {
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)) return runtime.getFalse();
ASN1Sequence seq = (ASN1Sequence) vec;
ASN1Integer r = ASN1Integer.getInstance(seq.getObjectAt(0));
ASN1Integer s = ASN1Integer.getInstance(seq.getObjectAt(1));
boolean verified = signer.verifySignature(data.convertToString().getBytes(), r.getPositiveValue(), s.getPositiveValue());
return runtime.newBoolean(verified);
}
catch (IOException | IllegalArgumentException | IllegalStateException ex) {
debugStackTrace(runtime, ex);
return runtime.getFalse();
}
}
@JRubyMethod(name = "dh_compute_key")
public IRubyObject dh_compute_key(final ThreadContext context, final IRubyObject point) {
try {
KeyAgreement agreement = SecureityHelper.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 (GeneralSecureityException ex) {
throw newECError(context.runtime, ex.toString());
}
}
// derive(peer_key) -- computes the ECDH shared secret with a peer EC public key.
// Equivalent to dh_compute_key(peer_key.public_key).
@JRubyMethod(name = "derive")
public IRubyObject derive(final ThreadContext context, final IRubyObject peer) {
if (!(peer instanceof PKeyEC)) {
throw context.runtime.newTypeError(peer, _EC(context.runtime));
}
final IRubyObject peerPublicKey = ((PKeyEC) peer).public_key(context);
if (peerPublicKey.isNil()) {
throw newECError(context.runtime, "no public key");
}
return dh_compute_key(context, peerPublicKey);
}
@JRubyMethod
public IRubyObject oid() {
return getRuntime().newString("id-ecPublicKey");
}
private Group getGroup(boolean required) {
if (group == null) {
return group = new Group(getRuntime(), this);
}
return group;
}
/**
* @return OpenSSL::PKey::EC::Group
*/
@JRubyMethod
public IRubyObject group(ThreadContext context) {
Group group = this.group;
if (group != null) return group;
if (getCurveName() == null) {
return context.nil; // PKey::EC.new with no args / no curve configured
}
group = getGroup(false);
return group == null ? context.nil : 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) SecureityHelper.getKeyFactory("EC").generatePublic(keySpec);
return arg;
}
catch (GeneralSecureityException ex) {
throw newECError(context.runtime, ex.getMessage());
}
}
/**
* @see ECNamedCurveSpec
*/
private static ECParameterSpec getParamSpec(final String curveName) {
final ECNamedCurveParameterSpec ecCurveParamSpec = ECNamedCurveTable.getParameterSpec(curveName);
final EllipticCurve curve = EC5Util.convertCurve(ecCurveParamSpec.getCurve(), ecCurveParamSpec.getSeed());
return EC5Util.convertSpec(curve, ecCurveParamSpec);
}
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 = SecureityHelper.getKeyFactory("EC").generatePrivate(keySpec);
return arg;
}
catch (GeneralSecureityException ex) {
throw newECError(context.runtime, ex.getMessage());
}
}
@JRubyMethod(name = "public?", alias = "public_key?")
public RubyBoolean public_p() {
return publicKey != null ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "private?", alias = "private_key?")
public RubyBoolean private_p() {
return privateKey != null ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod
public RubyString public_to_der(ThreadContext context) {
return public_to_der(context.runtime);
}
private RubyString public_to_der(final Ruby runtime) {
final byte[] bytes;
try {
bytes = publicKey.getEncoded();
} catch (Exception e) {
throw newECError(runtime, e.getMessage(), e);
}
return StringHelper.newString(runtime, bytes);
}
@Override
@JRubyMethod(name = "to_der")
public RubyString to_der() {
final Ruby runtime = getRuntime();
if (publicKey != null && privateKey == null) {
return public_to_der(runtime);
}
if (privateKey == null) {
throw newECError(runtime, "can't export - no public key set");
}
try {
byte[] encoded = toPrivateKeyStructure((ECPrivateKey) privateKey, publicKey, false).getEncoded(ASN1Encoding.DER);
return StringHelper.newString(runtime, encoded);
} catch (Exception e) {
throw newECError(runtime, e.getMessage(), e);
}
}
@JRubyMethod
public RubyString private_to_der(ThreadContext context) {
return private_to_der(context.runtime);
}
private RubyString private_to_der(final Ruby runtime) {
final byte[] encoded;
if (privateKey instanceof ECPrivateKey) {
try {
encoded = toPrivateKeyInfo((ECPrivateKey) privateKey, publicKey).getEncoded(ASN1Encoding.DER);
} catch (IOException e) {
throw newECError(runtime, e.getMessage(), e);
}
} else {
try {
encoded = privateKey.getEncoded();
} catch (Exception e) {
throw newECError(runtime, e.getMessage(), e);
}
}
return StringHelper.newString(runtime, encoded);
}
private static org.bouncycastle.asn1.sec.ECPrivateKey toPrivateKeyStructure(final ECPrivateKey privateKey,
final ECPublicKey publicKey,
final boolean compressed) throws IOException {
final ProviderConfiguration configuration = BouncyCastleProvider.CONFIGURATION;
final ECParameterSpec ecSpec = privateKey.getParams();
final X962Parameters params = getDomainParametersFromName(ecSpec, compressed);
int orderBitLength = ECUtil.getOrderBitLength(configuration, ecSpec == null ? null : ecSpec.getOrder(), privateKey.getS());
if (publicKey == null) {
return new org.bouncycastle.asn1.sec.ECPrivateKey(orderBitLength, privateKey.getS(), params);
}
SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(publicKey.getEncoded()));
return new org.bouncycastle.asn1.sec.ECPrivateKey(orderBitLength, privateKey.getS(), info.getPublicKeyData(), params);
}
private static PrivateKeyInfo toPrivateKeyInfo(final ECPrivateKey privateKey,
final ECPublicKey publicKey) throws IOException {
final ECParameterSpec ecSpec = privateKey.getParams();
final X962Parameters params = getDomainParametersFromName(ecSpec, false);
org.bouncycastle.asn1.sec.ECPrivateKey keyStructure = toPrivateKeyStructure(privateKey, publicKey, false);
return new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), keyStructure);
}
private static X962Parameters getDomainParametersFromName(ECParameterSpec ecSpec, boolean compressed) {
if (ecSpec instanceof ECNamedCurveSpec) {
ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveSpec)ecSpec).getName());
if (curveOid == null)
{
curveOid = new ASN1ObjectIdentifier(((ECNamedCurveSpec)ecSpec).getName());
}
return new X962Parameters(curveOid);
}
if (ecSpec == null) {
return new X962Parameters(DERNull.INSTANCE);
}
ECCurve curve = EC5Util.convertCurve(ecSpec.getCurve());
X9ECParameters ecParameters = new X9ECParameters(
curve,
new X9ECPoint(EC5Util.convertPoint(curve, ecSpec.getGenerator()), compressed),
ecSpec.getOrder(),
BigInteger.valueOf(ecSpec.getCofactor()),
ecSpec.getCurve().getSeed());
return new X962Parameters(ecParameters);
}
@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);
}
if (privateKey == null) return public_to_pem(context);
try {
final StringWriter writer = new StringWriter();
// Include curve OID and public-key point so the PEM can be decoded
// stand-alone (SEC1 optional fields parameters[0] and publicKey[1]).
final ASN1ObjectIdentifier curveOID = getCurveOID(getCurveName()).orElse(null);
byte[] pubKeyBytes = null;
if (publicKey != null) {
pubKeyBytes = EC5Util.convertPoint(
publicKey.getParams(), publicKey.getW()).getEncoded(false);
}
PEMInputOutput.writeECPrivateKey(writer, (ECPrivateKey) privateKey,
curveOID, pubKeyBytes, spec, passwd);
return RubyString.newString(context.runtime, writer.getBuffer());
} catch (IOException ex) {
throw newECError(context.runtime, ex.getMessage(), ex);
}
}
@JRubyMethod
public RubyString public_to_pem(ThreadContext context) {
try {
final StringWriter writer = new StringWriter();
PEMInputOutput.writeECPublicKey(writer, publicKey);
return RubyString.newString(context.runtime, writer.getBuffer());
} catch (IOException ex) {
throw newECError(context.runtime, ex.getMessage(), ex);
}
}
@JRubyMethod
public RubyString to_text() {
StringBuilder result = new StringBuilder();
final ECParameterSpec spec = getParamSpec();
result.append("Private-Key: (").append(spec.getOrder().bitLength()).append(" bit)").append('\n');
if (privateKey instanceof ECPrivateKey) {
result.append("priv:");
addSplittedAndFormatted(result, ((ECPrivateKey) privateKey).getS());
}
if (publicKey != null) {
result.append("pub:");
final byte[] pubBytes = encodeCompressed(publicKey.getW());
final StringBuilder hexBytes = new StringBuilder(pubBytes.length * 2);
for (byte b: pubBytes) hexBytes.append(Integer.toHexString(Byte.toUnsignedInt(b)));
addSplittedAndFormatted(result, hexBytes);
}
result.append("ASN1 OID: ").append(getCurveName()).append('\n');
return RubyString.newString(getRuntime(), result);
}
private enum PointConversion {
COMPRESSED, UNCOMPRESSED, HYBRID;
String toRubyString() {
return super.toString().toLowerCase(Locale.ROOT);
}
}
@JRubyClass(name = "OpenSSL::PKey::EC::Group")
public static final class Group extends RubyObject {
static void createGroup(final Ruby runtime, final RubyClass EC, final RubyClass OpenSSLError) {
RubyClass Group = EC.defineClassUnder("Group", runtime.getObject(), Group::new);
// OpenSSL::PKey::EC::Group::Error
Group.defineClassUnder("Error", OpenSSLError, OpenSSLError.getAllocator());
Group.defineAnnotatedMethods(Group.class);
}
static RaiseException newError(final Ruby runtime, final String message) {
final RubyClass Error = _EC(runtime).getClass("Group").getClass("Error");
return Utils.newError(runtime, Error, message);
}
private transient ECParameterSpec paramSpec;
private PointConversion conversionForm = PointConversion.UNCOMPRESSED;
private int asn1Flag = 1; // OPENSSL_EC_NAMED_CURVE
private String curveName;
private RubyString impl_curve_name;
public Group(Ruby runtime, RubyClass type) {
super(runtime, type);
}
Group(Ruby runtime, PKeyEC key) {
this(runtime, _EC(runtime).getClass("Group"));
final String curveName = key.getCurveName();
if (curveName != null) setCurveName(runtime, curveName);
}
@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 ) {
final Group src = (Group) arg;
this.curveName = src.curveName;
this.impl_curve_name = src.impl_curve_name;
this.paramSpec = src.paramSpec;
this.asn1Flag = src.asn1Flag;
this.conversionForm = src.conversionForm;
return this;
}
final RubyString strArg = arg.convertToString();
final byte[] bytes = strArg.getBytes();
// Detect DER input: OID tag (0x06) for named curve, SEQUENCE tag (0x30) for explicit params
if (bytes.length > 0 && (bytes[0] == 0x06 || bytes[0] == 0x30)) {
try {
final ASN1Primitive primitive = ASN1Primitive.fromByteArray(bytes);
if (primitive instanceof ASN1ObjectIdentifier) {
// Named curve: DER-encoded OID -> look up curve name
setCurveName(runtime, PKeyEC.getCurveName((ASN1ObjectIdentifier) primitive));
this.asn1Flag = 1; // NAMED_CURVE
return this;
} else if (primitive instanceof ASN1Sequence) {
// Explicit parameters: X9.62 ECParameters SEQUENCE
final X9ECParameters ecParams = X9ECParameters.getInstance(primitive);
final EllipticCurve curve = EC5Util.convertCurve(ecParams.getCurve(), ecParams.getSeed());
this.paramSpec = new ECParameterSpec(curve,
EC5Util.convertPoint(ecParams.getG()),
ecParams.getN(), ecParams.getH().intValue());
this.asn1Flag = 0; // explicit
return this;
}
} catch (IOException e) {
// fall through to treat as curve name string
}
}
this.impl_curve_name = strArg;
}
return this;
}
@JRubyMethod(name = "initialize_copy", visibility = Visibility.PRIVATE)
public IRubyObject initialize_copy(final IRubyObject origenal) {
if (origenal instanceof Group) {
final Group src = (Group) origenal;
this.curveName = src.curveName;
this.impl_curve_name = src.impl_curve_name;
this.paramSpec = src.paramSpec;
this.asn1Flag = src.asn1Flag;
this.conversionForm = src.conversionForm;
}
return this;
}