• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 public class OpenSSLRSAKeyPairGenerator extends KeyPairGeneratorSpi {
30     /**
31      * Default modulus size is 0x10001 (65537)
32      */
33     private byte[] publicExponent = new byte[] {
34             0x01, 0x00, 0x01
35     };
36 
37     /**
38      * Default RSA key size 2048 bits.
39      */
40     private int modulusBits = 2048;
41 
42     @Override
generateKeyPair()43     public KeyPair generateKeyPair() {
44         final OpenSSLKey key = new OpenSSLKey(NativeCrypto.RSA_generate_key_ex(modulusBits,
45                 publicExponent));
46 
47         PrivateKey privKey = OpenSSLRSAPrivateKey.getInstance(key);
48         PublicKey pubKey = new OpenSSLRSAPublicKey(key);
49 
50         return new KeyPair(pubKey, privKey);
51     }
52 
53     @Override
initialize(int keysize, SecureRandom random)54     public void initialize(int keysize, SecureRandom random) {
55         this.modulusBits = keysize;
56     }
57 
58     @Override
initialize(AlgorithmParameterSpec params, SecureRandom random)59     public void initialize(AlgorithmParameterSpec params, SecureRandom random)
60             throws InvalidAlgorithmParameterException {
61         if (!(params instanceof RSAKeyGenParameterSpec)) {
62             throw new InvalidAlgorithmParameterException("Only RSAKeyGenParameterSpec supported");
63         }
64 
65         RSAKeyGenParameterSpec spec = (RSAKeyGenParameterSpec) params;
66 
67         final BigInteger publicExponent = spec.getPublicExponent();
68         if (publicExponent != null) {
69             this.publicExponent = publicExponent.toByteArray();
70         }
71 
72         this.modulusBits = spec.getKeysize();
73     }
74 }
75