Search in sources :

Example 76 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.
     * @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} is {@code null}.
     */
public PKCS8EncodedKeySpec getKeySpec(Key decryptKey) throws NoSuchAlgorithmException, InvalidKeyException {
    if (decryptKey == null) {
        throw new NullPointerException("decryptKey == null");
    }
    try {
        Cipher cipher = Cipher.getInstance(algName);
        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 77 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 providerName
     *            the name of a provider whose cipher implementation should be
     *            used.
     * @return the extracted {@code PKCS8EncodedKeySpec}.
     * @throws NoSuchProviderException
     *             if no provider with {@code providerName} can be found.
     * @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 providerName} is {@code null}
     *             .
     */
public PKCS8EncodedKeySpec getKeySpec(Key decryptKey, String providerName) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException {
    if (decryptKey == null) {
        throw new NullPointerException("decryptKey == null");
    }
    if (providerName == null) {
        throw new NullPointerException("providerName == null");
    }
    try {
        Cipher cipher = Cipher.getInstance(algName, providerName);
        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 78 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 79 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 80 with PKCS8EncodedKeySpec

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

the class TestKeyStore method createCertificate.

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.
    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);
    BigInteger serial = BigInteger.valueOf(1);
    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha1WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha1WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }
    X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
    x509cg.setSubjectDN(subject);
    x509cg.setIssuerDN(issuer);
    x509cg.setNotBefore(start);
    x509cg.setNotAfter(end);
    x509cg.setPublicKey(publicKey);
    x509cg.setSignatureAlgorithm(signatureAlgorithm);
    x509cg.setSerialNumber(serial);
    if (keyUsage != 0) {
        x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    }
    for (int i = 0; i < extendedKeyUsages.size(); i++) {
        KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
        boolean critical = criticalExtendedKeyUsages.get(i);
        x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
    }
    for (GeneralName subjectAltName : subjectAltNames) {
        x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
    }
    if (privateKey instanceof ECPrivateKey) {
        /*
             * bouncycastle needs its own ECPrivateKey implementation
             */
        KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        privateKey = kf.generatePrivate(ks);
    }
    X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
    if (StandardNames.IS_RI) {
        /*
             * The RI can't handle the BC EC signature algorithm
             * string of "ECDSA", since it expects "...WITHEC...",
             * so convert from BC to RI X509Certificate
             * implementation via bytes.
             */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) NameConstraints(com.android.org.bouncycastle.asn1.x509.NameConstraints) KeyPurposeId(com.android.org.bouncycastle.asn1.x509.KeyPurposeId) ExtendedKeyUsage(com.android.org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(com.android.org.bouncycastle.asn1.x509.KeyUsage) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString) CertificateFactory(java.security.cert.CertificateFactory) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) GeneralNames(com.android.org.bouncycastle.asn1.x509.GeneralNames) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BigInteger(java.math.BigInteger) GeneralName(com.android.org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(com.android.org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(com.android.org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)227 KeyFactory (java.security.KeyFactory)179 PrivateKey (java.security.PrivateKey)148 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)50 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)47 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)40 PublicKey (java.security.PublicKey)39 IOException (java.io.IOException)30 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)30 SecretKey (javax.crypto.SecretKey)28 InvalidKeyException (java.security.InvalidKeyException)26 Key (java.security.Key)24 KeyStoreException (java.security.KeyStoreException)15