Search in sources :

Example 26 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project robovm by robovm.

the class EncryptedPrivateKeyInfo method getKeySpec.

/**
     * Returns the {@code PKCS8EncodedKeySpec} object extracted from the
     * encrypted data.
     *
     * @param decryptKey
     *            the key to decrypt the encrypted data with.
     * @param provider
     *            the provider whose cipher implementation should be used.
     * @return the extracted {@code PKCS8EncodedKeySpec}.
     * @throws NoSuchAlgorithmException
     *             if no usable cipher can be found to decrypt the encrypted
     *             data.
     * @throws InvalidKeyException
     *             if {@code decryptKey} is not usable to decrypt the encrypted
     *             data.
     * @throws NullPointerException
     *             if {@code decryptKey} or {@code provider} is {@code null}.
     */
public PKCS8EncodedKeySpec getKeySpec(Key decryptKey, Provider provider) throws NoSuchAlgorithmException, InvalidKeyException {
    if (decryptKey == null) {
        throw new NullPointerException("decryptKey == null");
    }
    if (provider == null) {
        throw new NullPointerException("provider == null");
    }
    try {
        Cipher cipher = Cipher.getInstance(algName, provider);
        if (algParameters == null) {
            cipher.init(Cipher.DECRYPT_MODE, decryptKey);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, decryptKey, algParameters);
        }
        byte[] decryptedData = cipher.doFinal(encryptedData);
        try {
            ASN1PrivateKeyInfo.verify(decryptedData);
        } catch (IOException e1) {
            throw invalidKey();
        }
        return new PKCS8EncodedKeySpec(decryptedData);
    } catch (NoSuchPaddingException e) {
        throw new NoSuchAlgorithmException(e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        throw new NoSuchAlgorithmException(e.getMessage());
    } catch (IllegalStateException e) {
        throw new InvalidKeyException(e.getMessage());
    } catch (IllegalBlockSizeException e) {
        throw new InvalidKeyException(e.getMessage());
    } catch (BadPaddingException e) {
        throw new InvalidKeyException(e.getMessage());
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 27 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project robovm by robovm.

the class X509KeyManagerTest method init.

void init(String name) {
    keyType = name;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        KeyFactory kf = KeyFactory.getInstance("RSA");
        keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
        keyTest.load(null, "1234".toCharArray());
        if (keyType.equals(CLIENT)) {
            keys = new PrivateKey[3];
            keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
            keys[1] = kf.generatePrivate(new PKCS8EncodedKeySpec(key2Bytes));
            keys[2] = kf.generatePrivate(new PKCS8EncodedKeySpec(key3Bytes));
            cert = new X509Certificate[3];
            cert[0] = (X509Certificate) cf.generateCertificate(certArray);
            cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
            cert[2] = (X509Certificate) cf.generateCertificate(certArray3);
            keyTest.setKeyEntry("clientKey_01", keys[0], PASSWORD, new X509Certificate[] { cert[0] });
            keyTest.setKeyEntry("clientKey_02", keys[1], PASSWORD, new X509Certificate[] { cert[0], cert[1] });
            keyTest.setKeyEntry("clientKey_03", keys[2], PASSWORD, new X509Certificate[] { cert[0], cert[2] });
            keyTest.setCertificateEntry("clientAlias_01", cert[0]);
            keyTest.setCertificateEntry("clientAlias_02", cert[0]);
            keyTest.setCertificateEntry("clientAlias_03", cert[1]);
        } else if (keyType.equals(SERVER)) {
            keys = new PrivateKey[1];
            keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
            cert = new X509Certificate[1];
            cert[0] = (X509Certificate) cf.generateCertificate(certArray3);
            keyTest.setKeyEntry("serverKey_00", keys[0], PASSWORD, new X509Certificate[] { cert[0] });
            keyTest.setCertificateEntry("serverAlias_00", cert[0]);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new IllegalArgumentException(ex.getMessage());
    }
    try {
        factory.init(keyTest, "1234".toCharArray());
    } catch (Exception e) {
        fail("Could't init the KeyManagerFactory");
    }
    manager = (X509KeyManager) factory.getKeyManagers()[0];
}
Also used : PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) CertificateFactory(java.security.cert.CertificateFactory) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 28 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project robovm by robovm.

the class KeyFactory2Test method test_generatePrivateLjava_security_spec_KeySpec.

public void test_generatePrivateLjava_security_spec_KeySpec() throws Exception {
    // java.security.KeyFactory.generatePrivate(java.security.spec.KeySpec)
    for (int i = 0; i < keyfactAlgs.length; i++) {
        KeyFactory fact = KeyFactory.getInstance(keyfactAlgs[i], providerName);
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyfactAlgs[i]);
        // We don't use
        SecureRandom random = new SecureRandom();
        // getInstance
        keyGen.initialize(StandardNames.getMinimumKeySize(keyfactAlgs[i]), random);
        KeepAlive keepalive = createKeepAlive(keyfactAlgs[i]);
        KeyPair keys = keyGen.generateKeyPair();
        if (keepalive != null) {
            keepalive.interrupt();
        }
        KeySpec privateKeySpec = fact.getKeySpec(keys.getPrivate(), StandardNames.getPrivateKeySpecClass(keyfactAlgs[i]));
        PrivateKey privateKey = fact.generatePrivate(privateKeySpec);
        assertEquals("generatePrivate generated different key for algorithm " + keyfactAlgs[i], Arrays.toString(keys.getPrivate().getEncoded()), Arrays.toString(privateKey.getEncoded()));
        privateKey = fact.generatePrivate(new PKCS8EncodedKeySpec(keys.getPrivate().getEncoded()));
        assertEquals("generatePrivate generated different key for algorithm " + keyfactAlgs[i], Arrays.toString(keys.getPrivate().getEncoded()), Arrays.toString(privateKey.getEncoded()));
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeySpec(java.security.spec.KeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) KeyFactory(java.security.KeyFactory)

Example 29 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project robovm by robovm.

the class KeyFactory method engineGeneratePrivate.

protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
    if (keySpec instanceof PKCS8EncodedKeySpec) {
        try {
            PrivateKeyInfo info = PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec) keySpec).getEncoded());
            PrivateKey key = BouncyCastleProvider.getPrivateKey(info);
            if (key != null) {
                return key;
            }
            throw new InvalidKeySpecException("no factory found for OID: " + info.getPrivateKeyAlgorithm().getAlgorithm());
        } catch (Exception e) {
            throw new InvalidKeySpecException(e.toString());
        }
    }
    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
Also used : PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidKeyException(java.security.InvalidKeyException)

Example 30 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project scribejava by scribejava.

the class RSASha1SignatureServiceTest method getPrivateKey.

/**
     * Created primary key using openssl.
     *
     * openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj '/C=GB/ST=/L=Manchester/CN=www.example.com'
     * -keyout myrsakey.pem -out /tmp/myrsacert.pem openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8
     */
private static PrivateKey getPrivateKey() {
    final String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n" + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n" + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n" + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n" + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n" + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n" + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n" + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n" + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n" + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n" + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n" + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n" + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n" + "UHgqXmuvk2X/Ww==";
    try {
        final KeyFactory fac = KeyFactory.getInstance("RSA");
        final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str));
        return fac.generatePrivate(privKeySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
}
Also used : PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory)

Aggregations

PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)218 KeyFactory (java.security.KeyFactory)172 PrivateKey (java.security.PrivateKey)144 CertificateFactory (java.security.cert.CertificateFactory)86 ByteArrayInputStream (java.io.ByteArrayInputStream)85 Certificate (java.security.cert.Certificate)72 X509Certificate (java.security.cert.X509Certificate)71 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)59 Entry (java.security.KeyStore.Entry)53 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)53 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)45 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)42 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)37 PublicKey (java.security.PublicKey)36 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)29 IOException (java.io.IOException)28 SecretKey (javax.crypto.SecretKey)27 InvalidKeyException (java.security.InvalidKeyException)25 Key (java.security.Key)24 KeyStoreException (java.security.KeyStoreException)15