Java Code Examples for java.security.KeyFactory#getKeySpec()

The following examples show how to use java.security.KeyFactory#getKeySpec() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RsaKeyPairGen.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
public static void main( final String[] args ) throws Exception {
	final KeyPairGenerator kpGen = KeyPairGenerator.getInstance( "RSA" );
	kpGen.initialize( KEY_SIZE_BITS );
	final KeyPair kp = kpGen.generateKeyPair();
	
	final PublicKey  pubKey  = kp.getPublic();
	final PrivateKey privKey = kp.getPrivate();
    
	if ( DEBUG ) {
   		System.out.println( pubKey .getAlgorithm() + " " + pubKey .getFormat() + " " + pubKey .getEncoded().length );
   		System.out.println( privKey.getAlgorithm() + " " + privKey.getFormat() + " " + privKey.getEncoded().length );
	}
	
	final KeyFactory kf = KeyFactory.getInstance( "RSA" );
	final RSAPublicKeySpec  pubKeySpec  = kf.getKeySpec( pubKey , RSAPublicKeySpec .class );
	final RSAPrivateKeySpec privKeySpec = kf.getKeySpec( privKey, RSAPrivateKeySpec.class );
	
	if ( DEBUG ) {
		System.out.println( pubKeySpec .getModulus() + " " + pubKeySpec .getPublicExponent() );
		System.out.println( privKeySpec.getModulus() + " " + privKeySpec.getPrivateExponent() );
	}
	
	saveKey( pubKeySpec .getModulus(), pubKeySpec .getPublicExponent (), "w:/pubkey.rsa"  );
	saveKey( privKeySpec.getModulus(), privKeySpec.getPrivateExponent(), "w:/privkey.rsa" );
}
 
Example 2
Source File: DKIMSign.java    From james-project with Apache License 2.0 6 votes vote down vote up
private PrivateKey extractPrivateKey(InputStream rawKey, char[] passphrase) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    try (InputStreamReader pemReader = new InputStreamReader(rawKey)) {
        try (PEMParser pemParser = new PEMParser(pemReader)) {
            Object pemObject = pemParser.readObject();
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            KeyPair keyPair;
            if (pemObject instanceof PrivateKeyInfo) {
                return converter.getPrivateKey((PrivateKeyInfo)pemObject);
            }
            if (pemObject instanceof PEMEncryptedKeyPair) {
                PEMEncryptedKeyPair pemEncryptedKeyPair = (PEMEncryptedKeyPair) pemObject;
                PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase);
                keyPair = converter.getKeyPair(pemEncryptedKeyPair.decryptKeyPair(decProv));
            } else {
                keyPair = converter.getKeyPair((PEMKeyPair) pemObject);
            }

            KeyFactory keyFac = KeyFactory.getInstance("RSA");
            RSAPrivateCrtKeySpec privateKeySpec = keyFac.getKeySpec(keyPair.getPrivate(), RSAPrivateCrtKeySpec.class);

            return keyFac.generatePrivate(privateKeySpec);
        }
    }
}
 
Example 3
Source File: EncryptionManagerAPI23.java    From samples-android with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValidKeys() {
    try {
        Cipher cipher = createCipher(mTransformationString);
        PrivateKey key = (PrivateKey) mKeyStore.getKey(mKeyAlias, null);
        try {
            KeyFactory factory = KeyFactory.getInstance(key.getAlgorithm(), mKeyStoreName);
            KeyInfo keyInfo = factory.getKeySpec(key, KeyInfo.class);
        } catch (NoSuchProviderException | InvalidKeySpecException error) {
            Log.w(TAG, "Error during Read private key info: ", error);
            return false;
        }
        cipher.init(Cipher.DECRYPT_MODE, key);
    } catch (GeneralSecurityException e) {
        return false;
    }

    return true;
}
 
Example 4
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns base64 encoded PublicKey
 * @param key PublicKey
 * @return public key encoded string
 */
public static String encodePublicKey(PublicKey key) {
    try {
        KeyFactory keyFactory = CertUtils.getKeyFactory();
        if (keyFactory == null) return null;
        X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class);
        return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()), Charset.forName("UTF-8"));
    } catch (InvalidKeySpecException e) {
        s_logger.error("Unable to get KeyFactory:" + e.getMessage());
    }
    return null;
}
 
Example 5
Source File: AuthKeyGenerator.java    From sensorhub-cloud-iot with Apache License 2.0 5 votes vote down vote up
private boolean isInSecureHardware() {
    try {
        KeyFactory factory = KeyFactory.getInstance(privateKey.getAlgorithm(), keystoreName);
        KeyInfo keyInfo = factory.getKeySpec(privateKey, KeyInfo.class);
        return keyInfo.isInsideSecureHardware();
    } catch (GeneralSecurityException e) {
        Log.w(TAG, "Could not determine if private key is in secure hardware or not");
    }
    return false;
}
 
Example 6
Source File: TestKeyFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void testPublic(KeyFactory kf, PublicKey key) throws Exception {
    System.out.println("Testing public key...");
    PublicKey key2 = (PublicKey)kf.translateKey(key);
    KeySpec keySpec = kf.getKeySpec(key, ECPublicKeySpec.class);
    PublicKey key3 = kf.generatePublic(keySpec);
    KeySpec x509Spec = kf.getKeySpec(key, X509EncodedKeySpec.class);
    PublicKey key4 = kf.generatePublic(x509Spec);
    KeySpec x509Spec2 = new X509EncodedKeySpec(key.getEncoded());
    PublicKey key5 = kf.generatePublic(x509Spec2);
    testKey(key, key);
    testKey(key, key2);
    testKey(key, key3);
    testKey(key, key4);
    testKey(key, key5);
}
 
Example 7
Source File: DHKeyExchange.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) {
    if (key instanceof DHPublicKey) {
        DHPublicKey dhKey = (DHPublicKey)key;
        DHParameterSpec params = dhKey.getParams();
        return new DHPublicKeySpec(dhKey.getY(),
                                params.getP(), params.getG());
    }
    try {
        KeyFactory factory = KeyFactory.getInstance("DiffieHellman");
        return factory.getKeySpec(key, DHPublicKeySpec.class);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        // unlikely
        throw new RuntimeException("Unable to get DHPublicKeySpec", e);
    }
}
 
Example 8
Source File: KeyInfoHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Converts a Java public key into a {@link DEREncodedKeyValue} element and adds it to
 * a {@link KeyInfo}.
 * 
 * @param keyInfo the {@link KeyInfo} element to which to add the key
 * @param pk the native Java {@link PublicKey} to add
 * @throws NoSuchAlgorithmException if the key type is unsupported
 * @throws InvalidKeySpecException if the key type does not support X.509 SPKI encoding
 */
public static void addDEREncodedPublicKey(KeyInfo keyInfo, PublicKey pk)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    DEREncodedKeyValue keyValue = (DEREncodedKeyValue) Configuration.getBuilderFactory()
        .getBuilder(DEREncodedKeyValue.DEFAULT_ELEMENT_NAME)
        .buildObject(DEREncodedKeyValue.DEFAULT_ELEMENT_NAME);
    
    KeyFactory keyFactory = KeyFactory.getInstance(pk.getAlgorithm());
    X509EncodedKeySpec keySpec = keyFactory.getKeySpec(pk, X509EncodedKeySpec.class);
    keyValue.setValue(Base64.encodeBytes(keySpec.getEncoded()));
    keyInfo.getXMLObjects().add(keyValue);
}
 
Example 9
Source File: DHKeyExchange.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
private static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) {
    if (key instanceof DHPublicKey) {
        DHPublicKey dhKey = (DHPublicKey)key;
        DHParameterSpec params = dhKey.getParams();
        return new DHPublicKeySpec(dhKey.getY(),
                                params.getP(), params.getG());
    }
    try {
        KeyFactory factory = JsseJce.getKeyFactory("DiffieHellman");
        return factory.getKeySpec(key, DHPublicKeySpec.class);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        // unlikely
        throw new RuntimeException("Unable to get DHPublicKeySpec", e);
    }
}
 
Example 10
Source File: KeyStoreCipher.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
public KeyInfo provideKeyInfo(String alias) {
    KeyInfo keyInfo = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alias = KEY_ALIAS_PREFIX + alias;

        try {
            KeyPair keyPair = getKeyPair(alias);
            KeyFactory factory = KeyFactory.getInstance(keyPair.getPrivate().getAlgorithm(), PROVIDER);
            keyInfo = factory.getKeySpec(keyPair.getPrivate(), KeyInfo.class);
        } catch (Exception ex) {
            LoggerHelper.e("KeyStoreCipher", ex.getMessage(), ex);
        }
    }
    return keyInfo;
}
 
Example 11
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var9) {
      throw new IllegalArgumentException(var9);
   }
}
 
Example 12
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var8) {
      throw new IllegalArgumentException(var8);
   }
}
 
Example 13
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var8) {
      throw new IllegalArgumentException(var8);
   }
}
 
Example 14
Source File: NewCertificateContract.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var9) {
      throw new IllegalArgumentException(var9);
   }
}
 
Example 15
Source File: KeySizeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int iKeyPairSize = Integer.parseInt(args[0]);
    int maxLoopCnt = Integer.parseInt(args[1]);

    int failCount = 0;
    KeyPairGenerator keyPairGen
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    keyPairGen.initialize(iKeyPairSize);
    // Generate RSA keypair
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // Get priavte and public keys
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    try {
        if (!sizeTest(keyPair)) {
            failCount++;
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        failCount++;
    }

    for (int iCnt = 0; iCnt < maxLoopCnt; iCnt++) {

        // Get keysize (modulus) of keys
        KeyFactory keyFact = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);

        // Comparing binary length.
        RSAPrivateKeySpec privateKeySpec
                = (RSAPrivateKeySpec) keyFact.getKeySpec(privateKey,
                        RSAPrivateKeySpec.class);
        int iPrivateKeySize = privateKeySpec.getModulus().bitLength();

        RSAPublicKeySpec publicKeySpec
                = (RSAPublicKeySpec) keyFact.getKeySpec(publicKey,
                        RSAPublicKeySpec.class);
        int iPublicKeySize = publicKeySpec.getModulus().bitLength();

        if ((iKeyPairSize != iPublicKeySize) || (iKeyPairSize != iPrivateKeySize)) {
            System.err.println("iKeyPairSize : " + iKeyPairSize);
            System.err.println("Generated a " + iPrivateKeySize
                    + " bit RSA private key");
            System.err.println("Generated a " + iPublicKeySize
                    + " bit RSA public key");
            failCount++;
        }
    }

    if (failCount > 0) {
        throw new RuntimeException("There are " + failCount + " tests failed.");
    }
}
 
Example 16
Source File: KeySizeTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int iKeyPairSize = Integer.parseInt(args[0]);
    int maxLoopCnt = Integer.parseInt(args[1]);

    int failCount = 0;
    KeyPairGenerator keyPairGen
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    keyPairGen.initialize(iKeyPairSize);
    // Generate RSA keypair
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // Get priavte and public keys
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    try {
        if (!sizeTest(keyPair)) {
            failCount++;
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        failCount++;
    }

    for (int iCnt = 0; iCnt < maxLoopCnt; iCnt++) {

        // Get keysize (modulus) of keys
        KeyFactory keyFact = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);

        // Comparing binary length.
        RSAPrivateKeySpec privateKeySpec
                = (RSAPrivateKeySpec) keyFact.getKeySpec(privateKey,
                        RSAPrivateKeySpec.class);
        int iPrivateKeySize = privateKeySpec.getModulus().bitLength();

        RSAPublicKeySpec publicKeySpec
                = (RSAPublicKeySpec) keyFact.getKeySpec(publicKey,
                        RSAPublicKeySpec.class);
        int iPublicKeySize = publicKeySpec.getModulus().bitLength();

        if ((iKeyPairSize != iPublicKeySize) || (iKeyPairSize != iPrivateKeySize)) {
            System.err.println("iKeyPairSize : " + iKeyPairSize);
            System.err.println("Generated a " + iPrivateKeySize
                    + " bit RSA private key");
            System.err.println("Generated a " + iPublicKeySize
                    + " bit RSA public key");
            failCount++;
        }
    }

    if (failCount > 0) {
        throw new RuntimeException("There are " + failCount + " tests failed.");
    }
}
 
Example 17
Source File: KeySizeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int iKeyPairSize = Integer.parseInt(args[0]);
    int maxLoopCnt = Integer.parseInt(args[1]);

    int failCount = 0;
    KeyPairGenerator keyPairGen
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    keyPairGen.initialize(iKeyPairSize);
    // Generate RSA keypair
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // Get priavte and public keys
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    try {
        if (!sizeTest(keyPair)) {
            failCount++;
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        failCount++;
    }

    for (int iCnt = 0; iCnt < maxLoopCnt; iCnt++) {

        // Get keysize (modulus) of keys
        KeyFactory keyFact = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);

        // Comparing binary length.
        RSAPrivateKeySpec privateKeySpec
                = (RSAPrivateKeySpec) keyFact.getKeySpec(privateKey,
                        RSAPrivateKeySpec.class);
        int iPrivateKeySize = privateKeySpec.getModulus().bitLength();

        RSAPublicKeySpec publicKeySpec
                = (RSAPublicKeySpec) keyFact.getKeySpec(publicKey,
                        RSAPublicKeySpec.class);
        int iPublicKeySize = publicKeySpec.getModulus().bitLength();

        if ((iKeyPairSize != iPublicKeySize) || (iKeyPairSize != iPrivateKeySize)) {
            System.err.println("iKeyPairSize : " + iKeyPairSize);
            System.err.println("Generated a " + iPrivateKeySize
                    + " bit RSA private key");
            System.err.println("Generated a " + iPublicKeySize
                    + " bit RSA public key");
            failCount++;
        }
    }

    if (failCount > 0) {
        throw new RuntimeException("There are " + failCount + " tests failed.");
    }
}
 
Example 18
Source File: KeySizeTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int iKeyPairSize = Integer.parseInt(args[0]);
    int maxLoopCnt = Integer.parseInt(args[1]);

    int failCount = 0;
    KeyPairGenerator keyPairGen
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    keyPairGen.initialize(iKeyPairSize);
    // Generate RSA keypair
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // Get priavte and public keys
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    try {
        if (!sizeTest(keyPair)) {
            failCount++;
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        failCount++;
    }

    for (int iCnt = 0; iCnt < maxLoopCnt; iCnt++) {

        // Get keysize (modulus) of keys
        KeyFactory keyFact = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);

        // Comparing binary length.
        RSAPrivateKeySpec privateKeySpec
                = (RSAPrivateKeySpec) keyFact.getKeySpec(privateKey,
                        RSAPrivateKeySpec.class);
        int iPrivateKeySize = privateKeySpec.getModulus().bitLength();

        RSAPublicKeySpec publicKeySpec
                = (RSAPublicKeySpec) keyFact.getKeySpec(publicKey,
                        RSAPublicKeySpec.class);
        int iPublicKeySize = publicKeySpec.getModulus().bitLength();

        if ((iKeyPairSize != iPublicKeySize) || (iKeyPairSize != iPrivateKeySize)) {
            System.err.println("iKeyPairSize : " + iKeyPairSize);
            System.err.println("Generated a " + iPrivateKeySize
                    + " bit RSA private key");
            System.err.println("Generated a " + iPublicKeySize
                    + " bit RSA public key");
            failCount++;
        }
    }

    if (failCount > 0) {
        throw new RuntimeException("There are " + failCount + " tests failed.");
    }
}
 
Example 19
Source File: KeySizeTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int iKeyPairSize = Integer.parseInt(args[0]);
    int maxLoopCnt = Integer.parseInt(args[1]);

    int failCount = 0;
    KeyPairGenerator keyPairGen
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    keyPairGen.initialize(iKeyPairSize);
    // Generate RSA keypair
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // Get priavte and public keys
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    try {
        if (!sizeTest(keyPair)) {
            failCount++;
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        failCount++;
    }

    for (int iCnt = 0; iCnt < maxLoopCnt; iCnt++) {

        // Get keysize (modulus) of keys
        KeyFactory keyFact = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);

        // Comparing binary length.
        RSAPrivateKeySpec privateKeySpec
                = (RSAPrivateKeySpec) keyFact.getKeySpec(privateKey,
                        RSAPrivateKeySpec.class);
        int iPrivateKeySize = privateKeySpec.getModulus().bitLength();

        RSAPublicKeySpec publicKeySpec
                = (RSAPublicKeySpec) keyFact.getKeySpec(publicKey,
                        RSAPublicKeySpec.class);
        int iPublicKeySize = publicKeySpec.getModulus().bitLength();

        if ((iKeyPairSize != iPublicKeySize) || (iKeyPairSize != iPrivateKeySize)) {
            System.err.println("iKeyPairSize : " + iKeyPairSize);
            System.err.println("Generated a " + iPrivateKeySize
                    + " bit RSA private key");
            System.err.println("Generated a " + iPublicKeySize
                    + " bit RSA public key");
            failCount++;
        }
    }

    if (failCount > 0) {
        throw new RuntimeException("There are " + failCount + " tests failed.");
    }
}
 
Example 20
Source File: KeySizeTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int iKeyPairSize = Integer.parseInt(args[0]);
    int maxLoopCnt = Integer.parseInt(args[1]);

    int failCount = 0;
    KeyPairGenerator keyPairGen
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    keyPairGen.initialize(iKeyPairSize);
    // Generate RSA keypair
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // Get priavte and public keys
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    try {
        if (!sizeTest(keyPair)) {
            failCount++;
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        failCount++;
    }

    for (int iCnt = 0; iCnt < maxLoopCnt; iCnt++) {

        // Get keysize (modulus) of keys
        KeyFactory keyFact = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);

        // Comparing binary length.
        RSAPrivateKeySpec privateKeySpec
                = (RSAPrivateKeySpec) keyFact.getKeySpec(privateKey,
                        RSAPrivateKeySpec.class);
        int iPrivateKeySize = privateKeySpec.getModulus().bitLength();

        RSAPublicKeySpec publicKeySpec
                = (RSAPublicKeySpec) keyFact.getKeySpec(publicKey,
                        RSAPublicKeySpec.class);
        int iPublicKeySize = publicKeySpec.getModulus().bitLength();

        if ((iKeyPairSize != iPublicKeySize) || (iKeyPairSize != iPrivateKeySize)) {
            System.err.println("iKeyPairSize : " + iKeyPairSize);
            System.err.println("Generated a " + iPrivateKeySize
                    + " bit RSA private key");
            System.err.println("Generated a " + iPublicKeySize
                    + " bit RSA public key");
            failCount++;
        }
    }

    if (failCount > 0) {
        throw new RuntimeException("There are " + failCount + " tests failed.");
    }
}