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 17 package org.conscrypt; 18 19 import java.math.BigInteger; 20 import java.security.InvalidAlgorithmParameterException; 21 import java.security.KeyPair; 22 import java.security.KeyPairGeneratorSpi; 23 import java.security.PrivateKey; 24 import java.security.PublicKey; 25 import java.security.SecureRandom; 26 import java.security.spec.AlgorithmParameterSpec; 27 import java.security.spec.RSAKeyGenParameterSpec; 28 29 /** 30 * An implementation of {@link java.security.KeyPairGenerator} which uses BoringSSL to perform all 31 * the operations. 32 * 33 * @hide 34 */ 35 @Internal 36 public final class OpenSSLRSAKeyPairGenerator extends KeyPairGeneratorSpi { 37 /** 38 * Default modulus size is 0x10001 (65537) 39 */ 40 private byte[] publicExponent = new byte[] { 41 0x01, 0x00, 0x01 42 }; 43 44 /** 45 * Default RSA key size 2048 bits. 46 */ 47 private int modulusBits = 2048; 48 49 @Override 50 public KeyPair generateKeyPair() { 51 final OpenSSLKey key = new OpenSSLKey(NativeCrypto.RSA_generate_key_ex(modulusBits, 52 publicExponent)); 53 54 PrivateKey privKey = OpenSSLRSAPrivateKey.getInstance(key); 55 PublicKey pubKey = new OpenSSLRSAPublicKey(key); 56 57 return new KeyPair(pubKey, privKey); 58 } 59 60 @Override 61 public void initialize(int keysize, SecureRandom random) { 62 this.modulusBits = keysize; 63 } 64 65 @Override 66 public void initialize(AlgorithmParameterSpec params, SecureRandom random) 67 throws InvalidAlgorithmParameterException { 68 if (!(params instanceof RSAKeyGenParameterSpec)) { 69 throw new InvalidAlgorithmParameterException("Only RSAKeyGenParameterSpec supported"); 70 } 71 72 RSAKeyGenParameterSpec spec = (RSAKeyGenParameterSpec) params; 73 74 final BigInteger publicExponent = spec.getPublicExponent(); 75 if (publicExponent != null) { 76 this.publicExponent = publicExponent.toByteArray(); 77 } 78 79 this.modulusBits = spec.getKeysize(); 80 } 81 } 82