DSAParameterGenerator.java 11.3 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
 */

package sun.security.provider;

import java.math.BigInteger;
import java.security.AlgorithmParameterGeneratorSpi;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.InvalidParameterException;
35
import java.security.MessageDigest;
D
duke 已提交
36
import java.security.SecureRandom;
37
import java.security.ProviderException;
D
duke 已提交
38 39 40
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.DSAParameterSpec;
41
import java.security.spec.DSAGenParameterSpec;
D
duke 已提交
42

43 44 45 46
import static sun.security.util.SecurityProviderConstants.DEF_DSA_KEY_SIZE;
import static sun.security.util.SecurityProviderConstants.getDefDSASubprimeSize;


D
duke 已提交
47
/**
48
 * This class generates parameters for the DSA algorithm.
D
duke 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61
 *
 * @author Jan Luehe
 *
 *
 * @see java.security.AlgorithmParameters
 * @see java.security.spec.AlgorithmParameterSpec
 * @see DSAParameters
 *
 * @since 1.2
 */

public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {

62 63 64 65
    // the length of prime P, subPrime Q, and seed in bits
    private int valueL = -1;
    private int valueN = -1;
    private int seedLen = -1;
D
duke 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

    // the source of randomness
    private SecureRandom random;

    // useful constants
    private static final BigInteger ONE = BigInteger.valueOf(1);
    private static final BigInteger TWO = BigInteger.valueOf(2);

    public DSAParameterGenerator() {
    }

    /**
     * Initializes this parameter generator for a certain strength
     * and source of randomness.
     *
     * @param strength the strength (size of prime) in bits
     * @param random the source of randomness
     */
84
    @Override
D
duke 已提交
85
    protected void engineInit(int strength, SecureRandom random) {
86 87 88 89 90 91 92
        if ((strength >= 512) && (strength <= 1024) && (strength % 64 == 0)) {
            this.valueN = 160;
        } else if (strength == 2048) {
            this.valueN = 224;
        } else if (strength == 3072) {
            this.valueN = 256;
        } else {
93
            throw new InvalidParameterException(
94 95
                "Unexpected strength (size of prime): " + strength + ". " +
                "Prime size should be 512 - 1024, or 2048, 3072");
D
duke 已提交
96
        }
97
        this.valueL = strength;
98
        this.valueN = getDefDSASubprimeSize(strength);
99
        this.seedLen = valueN;
D
duke 已提交
100 101 102 103 104 105 106
        this.random = random;
    }

    /**
     * Initializes this parameter generator with a set of
     * algorithm-specific parameter generation values.
     *
107 108
     * @param genParamSpec the set of algorithm-specific parameter
     *        generation values
D
duke 已提交
109 110 111 112 113
     * @param random the source of randomness
     *
     * @exception InvalidAlgorithmParameterException if the given parameter
     * generation values are inappropriate for this parameter generator
     */
114
    @Override
D
duke 已提交
115
    protected void engineInit(AlgorithmParameterSpec genParamSpec,
116
            SecureRandom random) throws InvalidAlgorithmParameterException {
117
        if (!(genParamSpec instanceof DSAGenParameterSpec)) {
D
duke 已提交
118
            throw new InvalidAlgorithmParameterException("Invalid parameter");
119
        }
120
        DSAGenParameterSpec dsaGenParams = (DSAGenParameterSpec)genParamSpec;
121

122
        // directly initialize using the already validated values
123
        this.valueL = dsaGenParams.getPrimePLength();
124 125 126
        this.valueN = dsaGenParams.getSubprimeQLength();
        this.seedLen = dsaGenParams.getSeedLength();
        this.random = random;
D
duke 已提交
127 128 129 130 131 132 133
    }

    /**
     * Generates the parameters.
     *
     * @return the new AlgorithmParameters object
     */
134
    @Override
D
duke 已提交
135 136 137 138 139 140
    protected AlgorithmParameters engineGenerateParameters() {
        AlgorithmParameters algParams = null;
        try {
            if (this.random == null) {
                this.random = new SecureRandom();
            }
141
            if (valueL == -1) {
142
                engineInit(DEF_DSA_KEY_SIZE, this.random);
143 144 145
            }
            BigInteger[] pAndQ = generatePandQ(this.random, valueL,
                                               valueN, seedLen);
D
duke 已提交
146 147 148 149
            BigInteger paramP = pAndQ[0];
            BigInteger paramQ = pAndQ[1];
            BigInteger paramG = generateG(paramP, paramQ);

150 151
            DSAParameterSpec dsaParamSpec =
                new DSAParameterSpec(paramP, paramQ, paramG);
D
duke 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
            algParams = AlgorithmParameters.getInstance("DSA", "SUN");
            algParams.init(dsaParamSpec);
        } catch (InvalidParameterSpecException e) {
            // this should never happen
            throw new RuntimeException(e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            // this should never happen, because we provide it
            throw new RuntimeException(e.getMessage());
        } catch (NoSuchProviderException e) {
            // this should never happen, because we provide it
            throw new RuntimeException(e.getMessage());
        }

        return algParams;
    }

    /*
     * Generates the prime and subprime parameters for DSA,
     * using the provided source of randomness.
     * This method will generate new seeds until a suitable
     * seed has been found.
     *
     * @param random the source of randomness to generate the
     * seed
176 177 178
     * @param valueL the size of <code>p</code>, in bits.
     * @param valueN the size of <code>q</code>, in bits.
     * @param seedLen the length of <code>seed</code>, in bits.
D
duke 已提交
179 180 181
     *
     * @return an array of BigInteger, with <code>p</code> at index 0 and
     * <code>q</code> at index 1, the seed at index 2, and the counter value
182
     * at index 3.
D
duke 已提交
183
     */
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    private static BigInteger[] generatePandQ(SecureRandom random, int valueL,
                                              int valueN, int seedLen) {
        String hashAlg = null;
        if (valueN == 160) {
            hashAlg = "SHA";
        } else if (valueN == 224) {
            hashAlg = "SHA-224";
        } else if (valueN == 256) {
            hashAlg = "SHA-256";
        }
        MessageDigest hashObj = null;
        try {
            hashObj = MessageDigest.getInstance(hashAlg);
        } catch (NoSuchAlgorithmException nsae) {
            // should never happen
            nsae.printStackTrace();
        }
D
duke 已提交
201

202 203 204 205 206 207
        /* Step 3, 4: Useful variables */
        int outLen = hashObj.getDigestLength()*8;
        int n = (valueL - 1) / outLen;
        int b = (valueL - 1) % outLen;
        byte[] seedBytes = new byte[seedLen/8];
        BigInteger twoSl = TWO.pow(seedLen);
208
        int primeCertainty = 80; // for 1024-bit prime P
209 210 211
        if (valueL <= 1024) {
            primeCertainty = 80;
        } else if (valueL == 2048) {
212
            primeCertainty = 112;
213 214
        } else if (valueL == 3072) {
            primeCertainty = 128;
215
        }
D
duke 已提交
216

217 218 219
        if (primeCertainty < 0) {
            throw new ProviderException("Invalid valueL: " + valueL);
        }
220 221 222 223 224 225 226 227 228 229 230 231 232
        BigInteger resultP, resultQ, seed = null;
        int counter;
        while (true) {
            do {
                /* Step 5 */
                random.nextBytes(seedBytes);
                seed = new BigInteger(1, seedBytes);

                /* Step 6 */
                BigInteger U = new BigInteger(1, hashObj.digest(seedBytes)).
                    mod(TWO.pow(valueN - 1));

                /* Step 7 */
233 234 235 236
                resultQ = TWO.pow(valueN - 1)
                            .add(U)
                            .add(ONE)
                            .subtract(U.mod(TWO));
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
            } while (!resultQ.isProbablePrime(primeCertainty));

            /* Step 10 */
            BigInteger offset = ONE;
            /* Step 11 */
            for (counter = 0; counter < 4*valueL; counter++) {
                BigInteger V[] = new BigInteger[n + 1];
                /* Step 11.1 */
                for (int j = 0; j <= n; j++) {
                    BigInteger J = BigInteger.valueOf(j);
                    BigInteger tmp = (seed.add(offset).add(J)).mod(twoSl);
                    byte[] vjBytes = hashObj.digest(toByteArray(tmp));
                    V[j] = new BigInteger(1, vjBytes);
                }
                /* Step 11.2 */
                BigInteger W = V[0];
                for (int i = 1; i < n; i++) {
                    W = W.add(V[i].multiply(TWO.pow(i * outLen)));
                }
256 257
                W = W.add((V[n].mod(TWO.pow(b)))
                               .multiply(TWO.pow(n * outLen)));
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
                /* Step 11.3 */
                BigInteger twoLm1 = TWO.pow(valueL - 1);
                BigInteger X = W.add(twoLm1);
                /* Step 11.4, 11.5 */
                BigInteger c = X.mod(resultQ.multiply(TWO));
                resultP = X.subtract(c.subtract(ONE));
                /* Step 11.6, 11.7 */
                if (resultP.compareTo(twoLm1) > -1
                    && resultP.isProbablePrime(primeCertainty)) {
                    /* Step 11.8 */
                    BigInteger[] result = {resultP, resultQ, seed,
                                           BigInteger.valueOf(counter)};
                    return result;
                }
                /* Step 11.9 */
                offset = offset.add(BigInteger.valueOf(n)).add(ONE);
D
duke 已提交
274
             }
275 276
        }

D
duke 已提交
277 278 279 280 281 282 283 284 285 286
    }

    /*
     * Generates the <code>g</code> parameter for DSA.
     *
     * @param p the prime, <code>p</code>.
     * @param q the subprime, <code>q</code>.
     *
     * @param the <code>g</code>
     */
287
    private static BigInteger generateG(BigInteger p, BigInteger q) {
D
duke 已提交
288
        BigInteger h = ONE;
289
        /* Step 1 */
D
duke 已提交
290
        BigInteger pMinusOneOverQ = (p.subtract(ONE)).divide(q);
291 292 293 294
        BigInteger resultG = ONE;
        while (resultG.compareTo(TWO) < 0) {
            /* Step 3 */
            resultG = h.modPow(pMinusOneOverQ, p);
D
duke 已提交
295 296
            h = h.add(ONE);
        }
297
        return resultG;
D
duke 已提交
298 299 300 301 302 303
    }

    /*
     * Converts the result of a BigInteger.toByteArray call to an exact
     * signed magnitude representation for any positive number.
     */
304
    private static byte[] toByteArray(BigInteger bigInt) {
D
duke 已提交
305 306 307 308 309 310 311 312 313
        byte[] result = bigInt.toByteArray();
        if (result[0] == 0) {
            byte[] tmp = new byte[result.length - 1];
            System.arraycopy(result, 1, tmp, 0, tmp.length);
            result = tmp;
        }
        return result;
    }
}