DSAKeyPairGenerator.java 8.9 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
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
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
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.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37
 */

package sun.security.provider;

import java.math.BigInteger;

import java.security.*;
import java.security.SecureRandom;
import java.security.interfaces.DSAParams;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.DSAParameterSpec;

import sun.security.jca.JCAUtil;
38 39
import static sun.security.util.SecurityProviderConstants.DEF_DSA_KEY_SIZE;
import static sun.security.util.SecurityProviderConstants.getDefDSASubprimeSize;
D
duke 已提交
40 41 42 43 44 45 46 47 48 49

/**
 * This class generates DSA key parameters and public/private key
 * pairs according to the DSS standard NIST FIPS 186. It uses the
 * updated version of SHA, SHA-1 as described in FIPS 180-1.
 *
 * @author Benjamin Renaud
 * @author Andreas Sterbenz
 *
 */
50
class DSAKeyPairGenerator extends KeyPairGenerator {
D
duke 已提交
51

52 53 54
    /* Length for prime P and subPrime Q in bits */
    private int plen;
    private int qlen;
D
duke 已提交
55 56

    /* whether to force new parameters to be generated for each KeyPair */
57
    boolean forceNewParameters;
D
duke 已提交
58 59 60 61 62 63 64

    /* preset algorithm parameters. */
    private DSAParameterSpec params;

    /* The source of random bits to use */
    private SecureRandom random;

65
    DSAKeyPairGenerator(int defaultKeySize) {
D
duke 已提交
66
        super("DSA");
67
        initialize(defaultKeySize, null);
D
duke 已提交
68 69
    }

70 71 72 73 74 75 76 77 78
    private static void checkStrength(int sizeP, int sizeQ) {
        if ((sizeP >= 512) && (sizeP <= 1024) && (sizeP % 64 == 0)
            && sizeQ == 160) {
            // traditional - allow for backward compatibility
            // L=multiples of 64 and between 512 and 1024 (inclusive)
            // N=160
        } else if (sizeP == 2048 && (sizeQ == 224 || sizeQ == 256)) {
            // L=2048, N=224 or 256
        } else {
D
duke 已提交
79
            throw new InvalidParameterException
80 81
                ("Unsupported prime and subprime size combination: " +
                 sizeP + ", " + sizeQ);
D
duke 已提交
82 83 84 85
        }
    }

    public void initialize(int modlen, SecureRandom random) {
86
        init(modlen, random, false);
D
duke 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    }

    /**
     * Initializes the DSA object using a parameter object.
     *
     * @param params the parameter set to be used to generate
     * the keys.
     * @param random the source of randomness for this generator.
     *
     * @exception InvalidAlgorithmParameterException if the given parameters
     * are inappropriate for this key pair generator
     */
    public void initialize(AlgorithmParameterSpec params, SecureRandom random)
            throws InvalidAlgorithmParameterException {
        if (!(params instanceof DSAParameterSpec)) {
            throw new InvalidAlgorithmParameterException
                ("Inappropriate parameter");
        }
105
        init((DSAParameterSpec)params, random, false);
D
duke 已提交
106 107
    }

108 109 110 111 112 113 114 115 116 117 118 119
    void init(int modlen, SecureRandom random, boolean forceNew) {
        int subPrimeLen = getDefDSASubprimeSize(modlen);
        checkStrength(modlen, subPrimeLen);
        this.plen = modlen;
        this.qlen = subPrimeLen;
        this.params = null;
        this.random = random;
        this.forceNewParameters = forceNew;
    }

    void init(DSAParameterSpec params, SecureRandom random,
        boolean forceNew) {
120 121 122 123 124
        int sizeP = params.getP().bitLength();
        int sizeQ = params.getQ().bitLength();
        checkStrength(sizeP, sizeQ);
        this.plen = sizeP;
        this.qlen = sizeQ;
D
duke 已提交
125 126
        this.params = params;
        this.random = random;
127
        this.forceNewParameters = forceNew;
D
duke 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141
    }

    /**
     * Generates a pair of keys usable by any JavaSecurity compliant
     * DSA implementation.
     */
    public KeyPair generateKeyPair() {
        if (random == null) {
            random = JCAUtil.getSecureRandom();
        }
        DSAParameterSpec spec;
        try {
            if (forceNewParameters) {
                // generate new parameters each time
142
                spec = ParameterCache.getNewDSAParameterSpec(plen, qlen, random);
D
duke 已提交
143 144 145
            } else {
                if (params == null) {
                    params =
146
                        ParameterCache.getDSAParameterSpec(plen, qlen, random);
D
duke 已提交
147 148 149 150 151 152 153 154 155
                }
                spec = params;
            }
        } catch (GeneralSecurityException e) {
            throw new ProviderException(e);
        }
        return generateKeyPair(spec.getP(), spec.getQ(), spec.getG(), random);
    }

156
    private KeyPair generateKeyPair(BigInteger p, BigInteger q, BigInteger g,
D
duke 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
                                   SecureRandom random) {

        BigInteger x = generateX(random, q);
        BigInteger y = generateY(x, p, g);

        try {

            // See the comments in DSAKeyFactory, 4532506, and 6232513.

            DSAPublicKey pub;
            if (DSAKeyFactory.SERIAL_INTEROP) {
                pub = new DSAPublicKey(y, p, q, g);
            } else {
                pub = new DSAPublicKeyImpl(y, p, q, g);
            }
            DSAPrivateKey priv = new DSAPrivateKey(x, p, q, g);

            KeyPair pair = new KeyPair(pub, priv);
            return pair;
        } catch (InvalidKeyException e) {
            throw new ProviderException(e);
        }
    }

    /**
     * Generate the private key component of the key pair using the
     * provided source of random bits. This method uses the random but
     * source passed to generate a seed and then calls the seed-based
     * generateX method.
     */
    private BigInteger generateX(SecureRandom random, BigInteger q) {
        BigInteger x = null;
189
        byte[] temp = new byte[qlen];
D
duke 已提交
190
        while (true) {
191 192
            random.nextBytes(temp);
            x = new BigInteger(1, temp).mod(q);
D
duke 已提交
193
            if (x.signum() > 0 && (x.compareTo(q) < 0)) {
194
                return x;
D
duke 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
            }
        }
    }

    /**
     * Generate the public key component y of the key pair.
     *
     * @param x the private key component.
     *
     * @param p the base parameter.
     */
    BigInteger generateY(BigInteger x, BigInteger p, BigInteger g) {
        BigInteger y = g.modPow(x, p);
        return y;
    }

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    public static final class Current extends DSAKeyPairGenerator {
        public Current() {
            super(DEF_DSA_KEY_SIZE);
        }
    }

    public static final class Legacy extends DSAKeyPairGenerator
        implements java.security.interfaces.DSAKeyPairGenerator {

        public Legacy() {
            super(1024);
        }

        /**
         * Initializes the DSA key pair generator. If <code>genParams</code>
         * is false, a set of pre-computed parameters is used.
         */
        @Override
        public void initialize(int modlen, boolean genParams,
            SecureRandom random) throws InvalidParameterException {
            if (genParams) {
                super.init(modlen, random, true);
            } else {
                DSAParameterSpec cachedParams =
                    ParameterCache.getCachedDSAParameterSpec(modlen,
                        getDefDSASubprimeSize(modlen));
                if (cachedParams == null) {
                    throw new InvalidParameterException
                        ("No precomputed parameters for requested modulus" +
                         " size available");
                }
                super.init(cachedParams, random, false);
            }
        }

        /**
         * Initializes the DSA object using a DSA parameter object.
         *
         * @param params a fully initialized DSA parameter object.
         */
        @Override
        public void initialize(DSAParams params, SecureRandom random)
            throws InvalidParameterException {
            if (params == null) {
                throw new InvalidParameterException("Params must not be null");
             }
             DSAParameterSpec spec = new DSAParameterSpec
                 (params.getP(), params.getQ(), params.getG());
             super.init(spec, random, false);
        }
    }
D
duke 已提交
262
}