Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/ec/ECDSASignature.java
38830 views
1
/*
2
* Copyright (c) 2009, 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package sun.security.ec;
27
28
import java.nio.ByteBuffer;
29
30
import java.security.*;
31
import java.security.interfaces.*;
32
import java.security.spec.*;
33
import java.util.Optional;
34
35
import sun.security.jca.JCAUtil;
36
import sun.security.util.*;
37
import static sun.security.ec.ECOperations.IntermediateValueException;
38
39
/**
40
* ECDSA signature implementation. This class currently supports the
41
* following algorithm names:
42
*
43
* . "NONEwithECDSA"
44
* . "SHA1withECDSA"
45
* . "SHA224withECDSA"
46
* . "SHA256withECDSA"
47
* . "SHA384withECDSA"
48
* . "SHA512withECDSA"
49
*
50
* @since 1.7
51
*/
52
abstract class ECDSASignature extends SignatureSpi {
53
54
// message digest implementation we use
55
private final MessageDigest messageDigest;
56
57
// supplied entropy
58
private SecureRandom random;
59
60
// flag indicating whether the digest has been reset
61
private boolean needsReset;
62
63
// private key, if initialized for signing
64
private ECPrivateKey privateKey;
65
66
// public key, if initialized for verifying
67
private ECPublicKey publicKey;
68
69
// signature parameters
70
private ECParameterSpec sigParams = null;
71
72
/**
73
* Constructs a new ECDSASignature. Used by Raw subclass.
74
*
75
* @exception ProviderException if the native ECC library is unavailable.
76
*/
77
ECDSASignature() {
78
messageDigest = null;
79
}
80
81
/**
82
* Constructs a new ECDSASignature. Used by subclasses.
83
*/
84
ECDSASignature(String digestName) {
85
try {
86
messageDigest = MessageDigest.getInstance(digestName);
87
} catch (NoSuchAlgorithmException e) {
88
throw new ProviderException(e);
89
}
90
needsReset = false;
91
}
92
93
// Nested class for NONEwithECDSA signatures
94
public static final class Raw extends ECDSASignature {
95
96
// the longest supported digest is 512 bits (SHA-512)
97
private static final int RAW_ECDSA_MAX = 64;
98
99
private final byte[] precomputedDigest;
100
private int offset = 0;
101
102
public Raw() {
103
precomputedDigest = new byte[RAW_ECDSA_MAX];
104
}
105
106
// Stores the precomputed message digest value.
107
@Override
108
protected void engineUpdate(byte b) throws SignatureException {
109
if (offset >= precomputedDigest.length) {
110
offset = RAW_ECDSA_MAX + 1;
111
return;
112
}
113
precomputedDigest[offset++] = b;
114
}
115
116
// Stores the precomputed message digest value.
117
@Override
118
protected void engineUpdate(byte[] b, int off, int len)
119
throws SignatureException {
120
if (offset >= precomputedDigest.length) {
121
offset = RAW_ECDSA_MAX + 1;
122
return;
123
}
124
System.arraycopy(b, off, precomputedDigest, offset, len);
125
offset += len;
126
}
127
128
// Stores the precomputed message digest value.
129
@Override
130
protected void engineUpdate(ByteBuffer byteBuffer) {
131
int len = byteBuffer.remaining();
132
if (len <= 0) {
133
return;
134
}
135
if (offset + len >= precomputedDigest.length) {
136
offset = RAW_ECDSA_MAX + 1;
137
return;
138
}
139
byteBuffer.get(precomputedDigest, offset, len);
140
offset += len;
141
}
142
143
@Override
144
protected void resetDigest() {
145
offset = 0;
146
}
147
148
// Returns the precomputed message digest value.
149
@Override
150
protected byte[] getDigestValue() throws SignatureException {
151
if (offset > RAW_ECDSA_MAX) {
152
throw new SignatureException("Message digest is too long");
153
154
}
155
byte[] result = new byte[offset];
156
System.arraycopy(precomputedDigest, 0, result, 0, offset);
157
offset = 0;
158
159
return result;
160
}
161
}
162
163
// Nested class for SHA1withECDSA signatures
164
public static final class SHA1 extends ECDSASignature {
165
public SHA1() {
166
super("SHA1");
167
}
168
}
169
170
// Nested class for SHA224withECDSA signatures
171
public static final class SHA224 extends ECDSASignature {
172
public SHA224() {
173
super("SHA-224");
174
}
175
}
176
177
// Nested class for SHA256withECDSA signatures
178
public static final class SHA256 extends ECDSASignature {
179
public SHA256() {
180
super("SHA-256");
181
}
182
}
183
184
// Nested class for SHA384withECDSA signatures
185
public static final class SHA384 extends ECDSASignature {
186
public SHA384() {
187
super("SHA-384");
188
}
189
}
190
191
// Nested class for SHA512withECDSA signatures
192
public static final class SHA512 extends ECDSASignature {
193
public SHA512() {
194
super("SHA-512");
195
}
196
}
197
198
// initialize for verification. See JCA doc
199
@Override
200
protected void engineInitVerify(PublicKey publicKey)
201
throws InvalidKeyException {
202
ECPublicKey key = (ECPublicKey) ECKeyFactory.toECKey(publicKey);
203
if (!isCompatible(this.sigParams, key.getParams())) {
204
throw new InvalidKeyException("Key params does not match signature params");
205
}
206
207
// Should check that the supplied key is appropriate for signature
208
// algorithm (e.g. P-256 for SHA256withECDSA)
209
this.publicKey = key;
210
this.privateKey = null;
211
resetDigest();
212
}
213
214
// initialize for signing. See JCA doc
215
@Override
216
protected void engineInitSign(PrivateKey privateKey)
217
throws InvalidKeyException {
218
engineInitSign(privateKey, null);
219
}
220
221
// initialize for signing. See JCA doc
222
@Override
223
protected void engineInitSign(PrivateKey privateKey, SecureRandom random)
224
throws InvalidKeyException {
225
ECPrivateKey key = (ECPrivateKey) ECKeyFactory.toECKey(privateKey);
226
if (!isCompatible(this.sigParams, key.getParams())) {
227
throw new InvalidKeyException("Key params does not match signature params");
228
}
229
230
// Should check that the supplied key is appropriate for signature
231
// algorithm (e.g. P-256 for SHA256withECDSA)
232
this.privateKey = key;
233
this.publicKey = null;
234
this.random = random;
235
resetDigest();
236
}
237
238
/**
239
* Resets the message digest if needed.
240
*/
241
protected void resetDigest() {
242
if (needsReset) {
243
if (messageDigest != null) {
244
messageDigest.reset();
245
}
246
needsReset = false;
247
}
248
}
249
250
/**
251
* Returns the message digest value.
252
*/
253
protected byte[] getDigestValue() throws SignatureException {
254
needsReset = false;
255
return messageDigest.digest();
256
}
257
258
// update the signature with the plaintext data. See JCA doc
259
@Override
260
protected void engineUpdate(byte b) throws SignatureException {
261
messageDigest.update(b);
262
needsReset = true;
263
}
264
265
// update the signature with the plaintext data. See JCA doc
266
@Override
267
protected void engineUpdate(byte[] b, int off, int len)
268
throws SignatureException {
269
messageDigest.update(b, off, len);
270
needsReset = true;
271
}
272
273
// update the signature with the plaintext data. See JCA doc
274
@Override
275
protected void engineUpdate(ByteBuffer byteBuffer) {
276
int len = byteBuffer.remaining();
277
if (len <= 0) {
278
return;
279
}
280
281
messageDigest.update(byteBuffer);
282
needsReset = true;
283
}
284
285
private static boolean isCompatible(ECParameterSpec sigParams,
286
ECParameterSpec keyParams) {
287
if (sigParams == null) {
288
// no restriction on key param
289
return true;
290
}
291
return ECUtil.equals(sigParams, keyParams);
292
}
293
294
295
private byte[] signDigestImpl(ECDSAOperations ops, int seedBits,
296
byte[] digest, ECPrivateKeyImpl privImpl, SecureRandom random)
297
throws SignatureException {
298
299
byte[] seedBytes = new byte[(seedBits + 7) / 8];
300
byte[] s = privImpl.getArrayS();
301
302
// Attempt to create the signature in a loop that uses new random input
303
// each time. The chance of failure is very small assuming the
304
// implementation derives the nonce using extra bits
305
int numAttempts = 128;
306
for (int i = 0; i < numAttempts; i++) {
307
random.nextBytes(seedBytes);
308
ECDSAOperations.Seed seed = new ECDSAOperations.Seed(seedBytes);
309
try {
310
return ops.signDigest(s, digest, seed);
311
} catch (IntermediateValueException ex) {
312
// try again in the next iteration
313
}
314
}
315
316
throw new SignatureException("Unable to produce signature after "
317
+ numAttempts + " attempts");
318
}
319
320
321
private Optional<byte[]> signDigestImpl(ECPrivateKey privateKey,
322
byte[] digest, SecureRandom random) throws SignatureException {
323
324
if (! (privateKey instanceof ECPrivateKeyImpl)) {
325
return Optional.empty();
326
}
327
ECPrivateKeyImpl privImpl = (ECPrivateKeyImpl) privateKey;
328
ECParameterSpec params = privateKey.getParams();
329
330
// seed is the key size + 64 bits
331
int seedBits = params.getOrder().bitLength() + 64;
332
Optional<ECDSAOperations> opsOpt =
333
ECDSAOperations.forParameters(params);
334
if (!opsOpt.isPresent()) {
335
return Optional.empty();
336
} else {
337
byte[] sig = signDigestImpl(opsOpt.get(), seedBits, digest,
338
privImpl, random);
339
return Optional.of(sig);
340
}
341
}
342
343
private byte[] signDigestNative(ECPrivateKey privateKey, byte[] digest,
344
SecureRandom random) throws SignatureException {
345
346
byte[] s = privateKey.getS().toByteArray();
347
ECParameterSpec params = privateKey.getParams();
348
349
// DER OID
350
byte[] encodedParams = ECUtil.encodeECParameterSpec(null, params);
351
int orderLength = params.getOrder().bitLength();
352
353
// seed is twice the order length (in bytes) plus 1
354
byte[] seed = new byte[(((orderLength + 7) >> 3) + 1) * 2];
355
356
random.nextBytes(seed);
357
358
// random bits needed for timing countermeasures
359
int timingArgument = random.nextInt();
360
// values must be non-zero to enable countermeasures
361
timingArgument |= 1;
362
363
try {
364
return signDigest(digest, s, encodedParams, seed,
365
timingArgument);
366
} catch (GeneralSecurityException e) {
367
throw new SignatureException("Could not sign data", e);
368
}
369
}
370
371
// sign the data and return the signature. See JCA doc
372
@Override
373
protected byte[] engineSign() throws SignatureException {
374
375
if (random == null) {
376
random = JCAUtil.getSecureRandom();
377
}
378
379
byte[] digest = getDigestValue();
380
Optional<byte[]> sigOpt = signDigestImpl(privateKey, digest, random);
381
byte[] sig;
382
if (sigOpt.isPresent()) {
383
sig = sigOpt.get();
384
} else {
385
sig = signDigestNative(privateKey, digest, random);
386
}
387
388
return ECUtil.encodeSignature(sig);
389
}
390
391
// verify the data and return the result. See JCA doc
392
@Override
393
protected boolean engineVerify(byte[] signature) throws SignatureException {
394
395
byte[] w;
396
ECParameterSpec params = publicKey.getParams();
397
// DER OID
398
byte[] encodedParams = ECUtil.encodeECParameterSpec(null, params);
399
400
if (publicKey instanceof ECPublicKeyImpl) {
401
w = ((ECPublicKeyImpl) publicKey).getEncodedPublicValue();
402
} else { // instanceof ECPublicKey
403
w = ECUtil.encodePoint(publicKey.getW(), params.getCurve());
404
}
405
406
try {
407
408
return verifySignedDigest(
409
ECUtil.decodeSignature(signature), getDigestValue(),
410
w, encodedParams);
411
412
} catch (GeneralSecurityException e) {
413
throw new SignatureException("Could not verify signature", e);
414
}
415
}
416
417
// set parameter, not supported. See JCA doc
418
@Override
419
@Deprecated
420
protected void engineSetParameter(String param, Object value)
421
throws InvalidParameterException {
422
throw new UnsupportedOperationException("setParameter() not supported");
423
}
424
425
@Override
426
protected void engineSetParameter(AlgorithmParameterSpec params)
427
throws InvalidAlgorithmParameterException {
428
if (params != null && !(params instanceof ECParameterSpec)) {
429
throw new InvalidAlgorithmParameterException("No parameter accepted");
430
}
431
ECKey key = (this.privateKey == null? this.publicKey : this.privateKey);
432
if ((key != null) && !isCompatible((ECParameterSpec)params, key.getParams())) {
433
throw new InvalidAlgorithmParameterException
434
("Signature params does not match key params");
435
}
436
437
sigParams = (ECParameterSpec) params;
438
}
439
440
// get parameter, not supported. See JCA doc
441
@Override
442
@Deprecated
443
protected Object engineGetParameter(String param)
444
throws InvalidParameterException {
445
throw new UnsupportedOperationException("getParameter() not supported");
446
}
447
448
@Override
449
protected AlgorithmParameters engineGetParameters() {
450
if (sigParams == null) {
451
return null;
452
}
453
try {
454
AlgorithmParameters ap = AlgorithmParameters.getInstance("EC");
455
ap.init(sigParams);
456
return ap;
457
} catch (Exception e) {
458
// should never happen
459
throw new ProviderException("Error retrieving EC parameters", e);
460
}
461
}
462
463
/**
464
* Signs the digest using the private key.
465
*
466
* @param digest the digest to be signed.
467
* @param s the private key's S value.
468
* @param encodedParams the curve's DER encoded object identifier.
469
* @param seed the random seed.
470
* @param timing When non-zero, the implmentation will use timing
471
* countermeasures to hide secrets from timing channels. The EC
472
* implementation will disable the countermeasures when this value is
473
* zero, because the underlying EC functions are shared by several
474
* crypto operations, some of which do not use the countermeasures.
475
* The high-order 31 bits must be uniformly random. The entropy from
476
* these bits is used by the countermeasures.
477
*
478
* @return byte[] the signature.
479
*/
480
private static native byte[] signDigest(byte[] digest, byte[] s,
481
byte[] encodedParams, byte[] seed, int timing)
482
throws GeneralSecurityException;
483
484
/**
485
* Verifies the signed digest using the public key.
486
*
487
* @param signature the signature to be verified. It is encoded
488
* as a concatenation of the key's R and S values.
489
* @param digest the digest to be used.
490
* @param w the public key's W point (in uncompressed form).
491
* @param encodedParams the curve's DER encoded object identifier.
492
*
493
* @return boolean true if the signature is successfully verified.
494
*/
495
private static native boolean verifySignedDigest(byte[] signature,
496
byte[] digest, byte[] w, byte[] encodedParams)
497
throws GeneralSecurityException;
498
}
499
500