Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/ec/ECKeyPairGenerator.java
38830 views
/*1* Copyright (c) 2009, 2018, 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.Optional;3637import sun.security.jca.JCAUtil;38import sun.security.util.ECUtil;39import sun.security.util.math.*;40import sun.security.ec.point.*;41import static sun.security.util.SecurityProviderConstants.DEF_EC_KEY_SIZE;42import static sun.security.ec.ECOperations.IntermediateValueException;4344/**45* EC keypair generator.46* Standard algorithm, minimum key length is 112 bits, maximum is 571 bits.47*48* @since 1.749*/50public final class ECKeyPairGenerator extends KeyPairGeneratorSpi {5152private static final int KEY_SIZE_MIN = 112; // min bits (see ecc_impl.h)53private static final int KEY_SIZE_MAX = 571; // max bits (see ecc_impl.h)5455// used to seed the keypair generator56private SecureRandom random;5758// size of the key to generate, KEY_SIZE_MIN <= keySize <= KEY_SIZE_MAX59private int keySize;6061// parameters specified via init, if any62private AlgorithmParameterSpec params = null;6364/**65* Constructs a new ECKeyPairGenerator.66*/67public ECKeyPairGenerator() {68// initialize to default in case the app does not call initialize()69initialize(DEF_EC_KEY_SIZE, null);70}7172// initialize the generator. See JCA doc73@Override74public void initialize(int keySize, SecureRandom random) {7576checkKeySize(keySize);77this.params = ECUtil.getECParameterSpec(null, keySize);78if (params == null) {79throw new InvalidParameterException(80"No EC parameters available for key size " + keySize + " bits");81}82this.random = random;83}8485// second initialize method. See JCA doc86@Override87public void initialize(AlgorithmParameterSpec params, SecureRandom random)88throws InvalidAlgorithmParameterException {8990ECParameterSpec ecSpec = null;9192if (params instanceof ECParameterSpec) {93ECParameterSpec ecParams = (ECParameterSpec) params;94ecSpec = ECUtil.getECParameterSpec(null, ecParams);95if (ecSpec == null) {96throw new InvalidAlgorithmParameterException(97"Unsupported curve: " + params);98}99} else if (params instanceof ECGenParameterSpec) {100String name = ((ECGenParameterSpec) params).getName();101ecSpec = ECUtil.getECParameterSpec(null, name);102if (ecSpec == null) {103throw new InvalidAlgorithmParameterException(104"Unknown curve name: " + name);105}106} else {107throw new InvalidAlgorithmParameterException(108"ECParameterSpec or ECGenParameterSpec required for EC");109}110111// Not all known curves are supported by the native implementation112ensureCurveIsSupported(ecSpec);113this.params = ecSpec;114115this.keySize = ecSpec.getCurve().getField().getFieldSize();116this.random = random;117}118119private static void ensureCurveIsSupported(ECParameterSpec ecSpec)120throws InvalidAlgorithmParameterException {121122AlgorithmParameters ecParams = ECUtil.getECParameters(null);123byte[] encodedParams;124try {125ecParams.init(ecSpec);126encodedParams = ecParams.getEncoded();127} catch (InvalidParameterSpecException ex) {128throw new InvalidAlgorithmParameterException(129"Unsupported curve: " + ecSpec.toString());130} catch (IOException ex) {131throw new RuntimeException(ex);132}133if (!isCurveSupported(encodedParams)) {134throw new InvalidAlgorithmParameterException(135"Unsupported curve: " + ecParams.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}152return generateKeyPairNative(random);153} catch (Exception ex) {154throw new ProviderException(ex);155}156}157158private byte[] generatePrivateScalar(SecureRandom random,159ECOperations ecOps, int seedSize) {160// Attempt to create the private scalar in a loop that uses new random161// input each time. The chance of failure is very small assuming the162// implementation derives the nonce using extra bits163int numAttempts = 128;164byte[] seedArr = new byte[seedSize];165for (int i = 0; i < numAttempts; i++) {166random.nextBytes(seedArr);167try {168return ecOps.seedToScalar(seedArr);169} catch (IntermediateValueException ex) {170// try again in the next iteration171}172}173174throw new ProviderException("Unable to produce private key after "175+ numAttempts + " attempts");176}177178private Optional<KeyPair> generateKeyPairImpl(SecureRandom random)179throws InvalidKeyException {180181ECParameterSpec ecParams = (ECParameterSpec) params;182183Optional<ECOperations> opsOpt = ECOperations.forParameters(ecParams);184if (!opsOpt.isPresent()) {185return Optional.empty();186}187ECOperations ops = opsOpt.get();188IntegerFieldModuloP field = ops.getField();189int numBits = ecParams.getOrder().bitLength();190int seedBits = numBits + 64;191int seedSize = (seedBits + 7) / 8;192byte[] privArr = generatePrivateScalar(random, ops, seedSize);193194ECPoint genPoint = ecParams.getGenerator();195ImmutableIntegerModuloP x = field.getElement(genPoint.getAffineX());196ImmutableIntegerModuloP y = field.getElement(genPoint.getAffineY());197AffinePoint affGen = new AffinePoint(x, y);198Point pub = ops.multiply(affGen, privArr);199AffinePoint affPub = pub.asAffine();200201PrivateKey privateKey = new ECPrivateKeyImpl(privArr, ecParams);202203ECPoint w = new ECPoint(affPub.getX().asBigInteger(),204affPub.getY().asBigInteger());205PublicKey publicKey = new ECPublicKeyImpl(w, ecParams);206207return Optional.of(new KeyPair(publicKey, privateKey));208}209210private KeyPair generateKeyPairNative(SecureRandom random)211throws Exception {212213ECParameterSpec ecParams = (ECParameterSpec) params;214byte[] encodedParams = ECUtil.encodeECParameterSpec(null, ecParams);215216// seed is twice the key size (in bytes) plus 1217byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];218random.nextBytes(seed);219Object[] keyBytes = generateECKeyPair(keySize, encodedParams, seed);220221// The 'params' object supplied above is equivalent to the native222// one so there is no need to fetch it.223// keyBytes[0] is the encoding of the native private key224BigInteger s = new BigInteger(1, (byte[]) keyBytes[0]);225226PrivateKey privateKey = new ECPrivateKeyImpl(s, ecParams);227228// keyBytes[1] is the encoding of the native public key229byte[] pubKey = (byte[]) keyBytes[1];230ECPoint w = ECUtil.decodePoint(pubKey, ecParams.getCurve());231PublicKey publicKey = new ECPublicKeyImpl(w, ecParams);232233return new KeyPair(publicKey, privateKey);234}235236private void checkKeySize(int keySize) throws InvalidParameterException {237if (keySize < KEY_SIZE_MIN) {238throw new InvalidParameterException239("Key size must be at least " + KEY_SIZE_MIN + " bits");240}241if (keySize > KEY_SIZE_MAX) {242throw new InvalidParameterException243("Key size must be at most " + KEY_SIZE_MAX + " bits");244}245this.keySize = keySize;246}247248/**249* Checks whether the curve in the encoded parameters is supported by the250* native implementation. Some curve operations will be performed by the251* Java implementation, but not all of them. So native support is still252* required for all curves.253*254* @param encodedParams encoded parameters in the same form accepted255* by generateECKeyPair256* @return true if and only if generateECKeyPair will succeed for257* the supplied parameters258*/259private static native boolean isCurveSupported(byte[] encodedParams);260261/*262* Generates the keypair and returns a 2-element array of encoding bytes.263* The first one is for the private key, the second for the public key.264*/265private static native Object[] generateECKeyPair(int keySize,266byte[] encodedParams, byte[] seed) throws GeneralSecurityException;267}268269270