1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package org.conscrypt; 18 19import java.math.BigInteger; 20import java.security.InvalidAlgorithmParameterException; 21import java.security.KeyPair; 22import java.security.KeyPairGeneratorSpi; 23import java.security.SecureRandom; 24import java.security.spec.AlgorithmParameterSpec; 25 26import javax.crypto.spec.DHParameterSpec; 27 28public class OpenSSLDHKeyPairGenerator extends KeyPairGeneratorSpi { 29 30 /** The safe prime to use for the generated DH key pair. */ 31 private BigInteger prime; 32 33 /** If {@code prime} is unspecified, this is the size of the generated prime. */ 34 private int primeBits = 1024; 35 36 private static final BigInteger DEFAULT_GENERATOR = BigInteger.valueOf(2); 37 38 private BigInteger generator = DEFAULT_GENERATOR; 39 40 @Override 41 public KeyPair generateKeyPair() { 42 final OpenSSLKey key; 43 if (prime != null) { 44 key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_DH(prime.toByteArray(), 45 generator.toByteArray(), null, null)); 46 } else { 47 key = new OpenSSLKey(NativeCrypto.DH_generate_parameters_ex(primeBits, 48 generator.longValue())); 49 } 50 51 NativeCrypto.DH_generate_key(key.getPkeyContext()); 52 53 final OpenSSLDHPrivateKey privKey = new OpenSSLDHPrivateKey(key); 54 final OpenSSLDHPublicKey pubKey = new OpenSSLDHPublicKey(key); 55 56 return new KeyPair(pubKey, privKey); 57 } 58 59 @Override 60 public void initialize(int keysize, SecureRandom random) { 61 prime = null; 62 primeBits = keysize; 63 generator = DEFAULT_GENERATOR; 64 } 65 66 @Override 67 public void initialize(AlgorithmParameterSpec params, SecureRandom random) 68 throws InvalidAlgorithmParameterException { 69 prime = null; 70 primeBits = 1024; 71 generator = DEFAULT_GENERATOR; 72 73 if (params instanceof DHParameterSpec) { 74 DHParameterSpec dhParams = (DHParameterSpec) params; 75 76 prime = dhParams.getP(); 77 BigInteger gen = dhParams.getG(); 78 if (gen != null) { 79 generator = gen; 80 } 81 } else if (params != null) { 82 throw new InvalidAlgorithmParameterException("Params must be DHParameterSpec"); 83 } 84 } 85} 86