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/ECKeyPairGenerator.java
38830 views
1
/*
2
* Copyright (c) 2009, 2018, 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.io.IOException;
29
import java.math.BigInteger;
30
import java.security.*;
31
import java.security.spec.AlgorithmParameterSpec;
32
import java.security.spec.ECGenParameterSpec;
33
import java.security.spec.ECParameterSpec;
34
import java.security.spec.ECPoint;
35
import java.security.spec.InvalidParameterSpecException;
36
import java.util.Optional;
37
38
import sun.security.jca.JCAUtil;
39
import sun.security.util.ECUtil;
40
import sun.security.util.math.*;
41
import sun.security.ec.point.*;
42
import static sun.security.util.SecurityProviderConstants.DEF_EC_KEY_SIZE;
43
import static sun.security.ec.ECOperations.IntermediateValueException;
44
45
/**
46
* EC keypair generator.
47
* Standard algorithm, minimum key length is 112 bits, maximum is 571 bits.
48
*
49
* @since 1.7
50
*/
51
public final class ECKeyPairGenerator extends KeyPairGeneratorSpi {
52
53
private static final int KEY_SIZE_MIN = 112; // min bits (see ecc_impl.h)
54
private static final int KEY_SIZE_MAX = 571; // max bits (see ecc_impl.h)
55
56
// used to seed the keypair generator
57
private SecureRandom random;
58
59
// size of the key to generate, KEY_SIZE_MIN <= keySize <= KEY_SIZE_MAX
60
private int keySize;
61
62
// parameters specified via init, if any
63
private AlgorithmParameterSpec params = null;
64
65
/**
66
* Constructs a new ECKeyPairGenerator.
67
*/
68
public ECKeyPairGenerator() {
69
// initialize to default in case the app does not call initialize()
70
initialize(DEF_EC_KEY_SIZE, null);
71
}
72
73
// initialize the generator. See JCA doc
74
@Override
75
public void initialize(int keySize, SecureRandom random) {
76
77
checkKeySize(keySize);
78
this.params = ECUtil.getECParameterSpec(null, keySize);
79
if (params == null) {
80
throw new InvalidParameterException(
81
"No EC parameters available for key size " + keySize + " bits");
82
}
83
this.random = random;
84
}
85
86
// second initialize method. See JCA doc
87
@Override
88
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
89
throws InvalidAlgorithmParameterException {
90
91
ECParameterSpec ecSpec = null;
92
93
if (params instanceof ECParameterSpec) {
94
ECParameterSpec ecParams = (ECParameterSpec) params;
95
ecSpec = ECUtil.getECParameterSpec(null, ecParams);
96
if (ecSpec == null) {
97
throw new InvalidAlgorithmParameterException(
98
"Unsupported curve: " + params);
99
}
100
} else if (params instanceof ECGenParameterSpec) {
101
String name = ((ECGenParameterSpec) params).getName();
102
ecSpec = ECUtil.getECParameterSpec(null, name);
103
if (ecSpec == null) {
104
throw new InvalidAlgorithmParameterException(
105
"Unknown curve name: " + name);
106
}
107
} else {
108
throw new InvalidAlgorithmParameterException(
109
"ECParameterSpec or ECGenParameterSpec required for EC");
110
}
111
112
// Not all known curves are supported by the native implementation
113
ensureCurveIsSupported(ecSpec);
114
this.params = ecSpec;
115
116
this.keySize = ecSpec.getCurve().getField().getFieldSize();
117
this.random = random;
118
}
119
120
private static void ensureCurveIsSupported(ECParameterSpec ecSpec)
121
throws InvalidAlgorithmParameterException {
122
123
AlgorithmParameters ecParams = ECUtil.getECParameters(null);
124
byte[] encodedParams;
125
try {
126
ecParams.init(ecSpec);
127
encodedParams = ecParams.getEncoded();
128
} catch (InvalidParameterSpecException ex) {
129
throw new InvalidAlgorithmParameterException(
130
"Unsupported curve: " + ecSpec.toString());
131
} catch (IOException ex) {
132
throw new RuntimeException(ex);
133
}
134
if (!isCurveSupported(encodedParams)) {
135
throw new InvalidAlgorithmParameterException(
136
"Unsupported curve: " + ecParams.toString());
137
}
138
}
139
140
// generate the keypair. See JCA doc
141
@Override
142
public KeyPair generateKeyPair() {
143
144
if (random == null) {
145
random = JCAUtil.getSecureRandom();
146
}
147
148
try {
149
Optional<KeyPair> kp = generateKeyPairImpl(random);
150
if (kp.isPresent()) {
151
return kp.get();
152
}
153
return generateKeyPairNative(random);
154
} catch (Exception ex) {
155
throw new ProviderException(ex);
156
}
157
}
158
159
private byte[] generatePrivateScalar(SecureRandom random,
160
ECOperations ecOps, int seedSize) {
161
// Attempt to create the private scalar in a loop that uses new random
162
// input each time. The chance of failure is very small assuming the
163
// implementation derives the nonce using extra bits
164
int numAttempts = 128;
165
byte[] seedArr = new byte[seedSize];
166
for (int i = 0; i < numAttempts; i++) {
167
random.nextBytes(seedArr);
168
try {
169
return ecOps.seedToScalar(seedArr);
170
} catch (IntermediateValueException ex) {
171
// try again in the next iteration
172
}
173
}
174
175
throw new ProviderException("Unable to produce private key after "
176
+ numAttempts + " attempts");
177
}
178
179
private Optional<KeyPair> generateKeyPairImpl(SecureRandom random)
180
throws InvalidKeyException {
181
182
ECParameterSpec ecParams = (ECParameterSpec) params;
183
184
Optional<ECOperations> opsOpt = ECOperations.forParameters(ecParams);
185
if (!opsOpt.isPresent()) {
186
return Optional.empty();
187
}
188
ECOperations ops = opsOpt.get();
189
IntegerFieldModuloP field = ops.getField();
190
int numBits = ecParams.getOrder().bitLength();
191
int seedBits = numBits + 64;
192
int seedSize = (seedBits + 7) / 8;
193
byte[] privArr = generatePrivateScalar(random, ops, seedSize);
194
195
ECPoint genPoint = ecParams.getGenerator();
196
ImmutableIntegerModuloP x = field.getElement(genPoint.getAffineX());
197
ImmutableIntegerModuloP y = field.getElement(genPoint.getAffineY());
198
AffinePoint affGen = new AffinePoint(x, y);
199
Point pub = ops.multiply(affGen, privArr);
200
AffinePoint affPub = pub.asAffine();
201
202
PrivateKey privateKey = new ECPrivateKeyImpl(privArr, ecParams);
203
204
ECPoint w = new ECPoint(affPub.getX().asBigInteger(),
205
affPub.getY().asBigInteger());
206
PublicKey publicKey = new ECPublicKeyImpl(w, ecParams);
207
208
return Optional.of(new KeyPair(publicKey, privateKey));
209
}
210
211
private KeyPair generateKeyPairNative(SecureRandom random)
212
throws Exception {
213
214
ECParameterSpec ecParams = (ECParameterSpec) params;
215
byte[] encodedParams = ECUtil.encodeECParameterSpec(null, ecParams);
216
217
// seed is twice the key size (in bytes) plus 1
218
byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
219
random.nextBytes(seed);
220
Object[] keyBytes = generateECKeyPair(keySize, encodedParams, seed);
221
222
// The 'params' object supplied above is equivalent to the native
223
// one so there is no need to fetch it.
224
// keyBytes[0] is the encoding of the native private key
225
BigInteger s = new BigInteger(1, (byte[]) keyBytes[0]);
226
227
PrivateKey privateKey = new ECPrivateKeyImpl(s, ecParams);
228
229
// keyBytes[1] is the encoding of the native public key
230
byte[] pubKey = (byte[]) keyBytes[1];
231
ECPoint w = ECUtil.decodePoint(pubKey, ecParams.getCurve());
232
PublicKey publicKey = new ECPublicKeyImpl(w, ecParams);
233
234
return new KeyPair(publicKey, privateKey);
235
}
236
237
private void checkKeySize(int keySize) throws InvalidParameterException {
238
if (keySize < KEY_SIZE_MIN) {
239
throw new InvalidParameterException
240
("Key size must be at least " + KEY_SIZE_MIN + " bits");
241
}
242
if (keySize > KEY_SIZE_MAX) {
243
throw new InvalidParameterException
244
("Key size must be at most " + KEY_SIZE_MAX + " bits");
245
}
246
this.keySize = keySize;
247
}
248
249
/**
250
* Checks whether the curve in the encoded parameters is supported by the
251
* native implementation. Some curve operations will be performed by the
252
* Java implementation, but not all of them. So native support is still
253
* required for all curves.
254
*
255
* @param encodedParams encoded parameters in the same form accepted
256
* by generateECKeyPair
257
* @return true if and only if generateECKeyPair will succeed for
258
* the supplied parameters
259
*/
260
private static native boolean isCurveSupported(byte[] encodedParams);
261
262
/*
263
* Generates the keypair and returns a 2-element array of encoding bytes.
264
* The first one is for the private key, the second for the public key.
265
*/
266
private static native Object[] generateECKeyPair(int keySize,
267
byte[] encodedParams, byte[] seed) throws GeneralSecurityException;
268
}
269
270