Path: blob/master/src/jdk.crypto.ec/share/classes/sun/security/ec/ECKeyPairGenerator.java
41161 views
/*1* Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.ec;2627import java.io.IOException;28import java.math.BigInteger;29import java.security.*;30import java.security.spec.AlgorithmParameterSpec;31import java.security.spec.ECGenParameterSpec;32import java.security.spec.ECParameterSpec;33import java.security.spec.ECPoint;34import java.security.spec.InvalidParameterSpecException;35import java.util.Arrays;36import java.util.Optional;3738import sun.security.jca.JCAUtil;39import sun.security.util.ECUtil;40import sun.security.util.math.*;41import sun.security.ec.point.*;42import static sun.security.util.SecurityProviderConstants.DEF_EC_KEY_SIZE;43import static sun.security.ec.ECOperations.IntermediateValueException;4445/**46* EC keypair generator.47* Standard algorithm, minimum key length is 112 bits, maximum is 571 bits.48*49* @since 1.750*/51public final class ECKeyPairGenerator extends KeyPairGeneratorSpi {5253private static final int KEY_SIZE_MIN = 112; // min bits (see ecc_impl.h)54private static final int KEY_SIZE_MAX = 571; // max bits (see ecc_impl.h)5556// used to seed the keypair generator57private SecureRandom random;5859// size of the key to generate, KEY_SIZE_MIN <= keySize <= KEY_SIZE_MAX60private int keySize;6162// parameters specified via init, if any63private AlgorithmParameterSpec params = null;6465/**66* Constructs a new ECKeyPairGenerator.67*/68public ECKeyPairGenerator() {69// initialize to default in case the app does not call initialize()70initialize(DEF_EC_KEY_SIZE, null);71}7273// initialize the generator. See JCA doc74@Override75public void initialize(int keySize, SecureRandom random) {7677checkKeySize(keySize);78this.params = ECUtil.getECParameterSpec(null, keySize);79if (params == null) {80throw new InvalidParameterException(81"No EC parameters available for key size " + keySize + " bits");82}83this.random = random;84}8586// second initialize method. See JCA doc87@Override88public void initialize(AlgorithmParameterSpec params, SecureRandom random)89throws InvalidAlgorithmParameterException {9091ECParameterSpec ecSpec = null;9293if (params instanceof ECParameterSpec) {94ECParameterSpec ecParams = (ECParameterSpec) params;95ecSpec = ECUtil.getECParameterSpec(null, ecParams);96if (ecSpec == null) {97throw new InvalidAlgorithmParameterException(98"Curve not supported: " + params);99}100} else if (params instanceof ECGenParameterSpec) {101String name = ((ECGenParameterSpec) params).getName();102ecSpec = ECUtil.getECParameterSpec(null, name);103if (ecSpec == null) {104throw new InvalidAlgorithmParameterException(105"Unknown curve name: " + name);106}107} else {108throw new InvalidAlgorithmParameterException(109"ECParameterSpec or ECGenParameterSpec required for EC");110}111112// Not all known curves are supported by the native implementation113ensureCurveIsSupported(ecSpec);114this.params = ecSpec;115116this.keySize = ecSpec.getCurve().getField().getFieldSize();117this.random = random;118}119120private static void ensureCurveIsSupported(ECParameterSpec ecSpec)121throws InvalidAlgorithmParameterException {122123// Check if ecSpec is a valid curve124AlgorithmParameters ecParams = ECUtil.getECParameters(null);125try {126ecParams.init(ecSpec);127} catch (InvalidParameterSpecException ex) {128throw new InvalidAlgorithmParameterException(129"Curve not supported: " + ecSpec.toString());130}131132// Check if the java implementation supports this curve133if (ECOperations.forParameters(ecSpec).isEmpty()) {134throw new InvalidAlgorithmParameterException(135"Curve not supported: " + ecSpec.toString());136}137}138139// generate the keypair. See JCA doc140@Override141public KeyPair generateKeyPair() {142143if (random == null) {144random = JCAUtil.getSecureRandom();145}146147try {148Optional<KeyPair> kp = generateKeyPairImpl(random);149if (kp.isPresent()) {150return kp.get();151}152} catch (Exception ex) {153throw new ProviderException(ex);154}155throw new ProviderException("Curve not supported: " +156params.toString());157}158159private byte[] generatePrivateScalar(SecureRandom random,160ECOperations ecOps, int seedSize) {161// Attempt to create the private scalar in a loop that uses new random162// input each time. The chance of failure is very small assuming the163// implementation derives the nonce using extra bits164int numAttempts = 128;165byte[] seedArr = new byte[seedSize];166for (int i = 0; i < numAttempts; i++) {167random.nextBytes(seedArr);168try {169return ecOps.seedToScalar(seedArr);170} catch (IntermediateValueException ex) {171// try again in the next iteration172}173}174175throw new ProviderException("Unable to produce private key after "176+ numAttempts + " attempts");177}178179private Optional<KeyPair> generateKeyPairImpl(SecureRandom random)180throws InvalidKeyException {181182ECParameterSpec ecParams = (ECParameterSpec) params;183184Optional<ECOperations> opsOpt = ECOperations.forParameters(ecParams);185if (opsOpt.isEmpty()) {186return Optional.empty();187}188ECOperations ops = opsOpt.get();189IntegerFieldModuloP field = ops.getField();190int numBits = ecParams.getOrder().bitLength();191int seedBits = numBits + 64;192int seedSize = (seedBits + 7) / 8;193byte[] privArr = generatePrivateScalar(random, ops, seedSize);194195ECPoint genPoint = ecParams.getGenerator();196ImmutableIntegerModuloP x = field.getElement(genPoint.getAffineX());197ImmutableIntegerModuloP y = field.getElement(genPoint.getAffineY());198AffinePoint affGen = new AffinePoint(x, y);199Point pub = ops.multiply(affGen, privArr);200AffinePoint affPub = pub.asAffine();201202PrivateKey privateKey = new ECPrivateKeyImpl(privArr, ecParams);203Arrays.fill(privArr, (byte)0);204205ECPoint w = new ECPoint(affPub.getX().asBigInteger(),206affPub.getY().asBigInteger());207PublicKey publicKey = new ECPublicKeyImpl(w, ecParams);208209return Optional.of(new KeyPair(publicKey, privateKey));210}211212private void checkKeySize(int keySize) throws InvalidParameterException {213if (keySize < KEY_SIZE_MIN) {214throw new InvalidParameterException215("Key size must be at least " + KEY_SIZE_MIN + " bits");216}217if (keySize > KEY_SIZE_MAX) {218throw new InvalidParameterException219("Key size must be at most " + KEY_SIZE_MAX + " bits");220}221this.keySize = keySize;222}223}224225226