ECKeyPairGenerator.java 7.6 KB
Newer Older
1
/*
2
 * Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * 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 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25 26 27
 */

package sun.security.ec;

28
import java.io.IOException;
29 30 31 32 33 34
import java.math.BigInteger;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
35
import java.security.spec.InvalidParameterSpecException;
36 37 38 39 40 41

import sun.security.ec.NamedCurve;
import sun.security.ec.ECParameters;
import sun.security.ec.ECPrivateKeyImpl;
import sun.security.ec.ECPublicKeyImpl;
import sun.security.jca.JCAUtil;
42
import sun.security.util.ECUtil;
43
import static sun.security.util.SecurityProviderConstants.DEF_EC_KEY_SIZE;
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

/**
 * EC keypair generator.
 * Standard algorithm, minimum key length is 112 bits, maximum is 571 bits.
 *
 * @since 1.7
 */
public final class ECKeyPairGenerator extends KeyPairGeneratorSpi {

    private static final int KEY_SIZE_MIN = 112; // min bits (see ecc_impl.h)
    private static final int KEY_SIZE_MAX = 571; // max bits (see ecc_impl.h)

    // used to seed the keypair generator
    private SecureRandom random;

    // size of the key to generate, KEY_SIZE_MIN <= keySize <= KEY_SIZE_MAX
    private int keySize;

    // parameters specified via init, if any
    private AlgorithmParameterSpec params = null;

    /**
     * Constructs a new ECKeyPairGenerator.
     */
    public ECKeyPairGenerator() {
        // initialize to default in case the app does not call initialize()
70
        initialize(DEF_EC_KEY_SIZE, null);
71 72 73 74 75 76 77
    }

    // initialize the generator. See JCA doc
    @Override
    public void initialize(int keySize, SecureRandom random) {

        checkKeySize(keySize);
78
        this.params = ECUtil.getECParameterSpec(null, keySize);
79 80 81 82 83 84 85 86 87 88 89 90
        if (params == null) {
            throw new InvalidParameterException(
                "No EC parameters available for key size " + keySize + " bits");
        }
        this.random = random;
    }

    // second initialize method. See JCA doc
    @Override
    public void initialize(AlgorithmParameterSpec params, SecureRandom random)
            throws InvalidAlgorithmParameterException {

91 92
        ECParameterSpec ecSpec = null;

93
        if (params instanceof ECParameterSpec) {
94
            ecSpec = ECUtil.getECParameterSpec(null,
95
                                                    (ECParameterSpec)params);
96
            if (ecSpec == null) {
97 98 99 100 101
                throw new InvalidAlgorithmParameterException(
                    "Unsupported curve: " + params);
            }
        } else if (params instanceof ECGenParameterSpec) {
            String name = ((ECGenParameterSpec)params).getName();
102 103
            ecSpec = ECUtil.getECParameterSpec(null, name);
            if (ecSpec == null) {
104 105 106 107 108 109 110
                throw new InvalidAlgorithmParameterException(
                    "Unknown curve name: " + name);
            }
        } else {
            throw new InvalidAlgorithmParameterException(
                "ECParameterSpec or ECGenParameterSpec required for EC");
        }
111 112 113 114 115

        // Not all known curves are supported by the native implementation
        ensureCurveIsSupported(ecSpec);
        this.params = ecSpec;

116 117 118 119 120
        this.keySize =
            ((ECParameterSpec)this.params).getCurve().getField().getFieldSize();
        this.random = random;
    }

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    private static void ensureCurveIsSupported(ECParameterSpec ecSpec)
        throws InvalidAlgorithmParameterException {

        AlgorithmParameters ecParams = ECUtil.getECParameters(null);
        byte[] encodedParams;
        try {
            ecParams.init(ecSpec);
            encodedParams = ecParams.getEncoded();
        } catch (InvalidParameterSpecException ex) {
            throw new InvalidAlgorithmParameterException(
                "Unsupported curve: " + ecSpec.toString());
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        if (!isCurveSupported(encodedParams)) {
            throw new InvalidAlgorithmParameterException(
                "Unsupported curve: " + ecParams.toString());
        }
    }

141 142 143 144 145
    // generate the keypair. See JCA doc
    @Override
    public KeyPair generateKeyPair() {

        byte[] encodedParams =
146
            ECUtil.encodeECParameterSpec(null, (ECParameterSpec)params);
147

148 149
        // seed is twice the key size (in bytes) plus 1
        byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
150 151 152 153 154
        if (random == null) {
            random = JCAUtil.getSecureRandom();
        }
        random.nextBytes(seed);

155
        try {
156

V
valeriep 已提交
157
            Object[] keyBytes = generateECKeyPair(keySize, encodedParams, seed);
158

159 160
            // The 'params' object supplied above is equivalent to the native
            // one so there is no need to fetch it.
V
valeriep 已提交
161 162
            // keyBytes[0] is the encoding of the native private key
            BigInteger s = new BigInteger(1, (byte[])keyBytes[0]);
163 164 165 166

            PrivateKey privateKey =
                new ECPrivateKeyImpl(s, (ECParameterSpec)params);

V
valeriep 已提交
167 168
            // keyBytes[1] is the encoding of the native public key
            ECPoint w = ECUtil.decodePoint((byte[])keyBytes[1],
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
                ((ECParameterSpec)params).getCurve());
            PublicKey publicKey =
                new ECPublicKeyImpl(w, (ECParameterSpec)params);

            return new KeyPair(publicKey, privateKey);

        } catch (Exception e) {
            throw new ProviderException(e);
        }
    }

    private void checkKeySize(int keySize) throws InvalidParameterException {
        if (keySize < KEY_SIZE_MIN) {
            throw new InvalidParameterException
                ("Key size must be at least " + KEY_SIZE_MIN + " bits");
        }
        if (keySize > KEY_SIZE_MAX) {
            throw new InvalidParameterException
                ("Key size must be at most " + KEY_SIZE_MAX + " bits");
        }
        this.keySize = keySize;
    }

192 193 194 195 196 197 198 199 200 201 202
    /**
     * Checks whether the curve in the encoded parameters is supported by the
     * native implementation.
     *
     * @param encodedParams encoded parameters in the same form accepted
     *    by generateECKeyPair
     * @return true if and only if generateECKeyPair will succeed for
     *    the supplied parameters
     */
    private static native boolean isCurveSupported(byte[] encodedParams);

203
    /*
V
valeriep 已提交
204 205
     * Generates the keypair and returns a 2-element array of encoding bytes.
     * The first one is for the private key, the second for the public key.
206
     */
V
valeriep 已提交
207
    private static native Object[] generateECKeyPair(int keySize,
208
        byte[] encodedParams, byte[] seed) throws GeneralSecurityException;
209
}