Search in sources :

Example 61 with Certificate

use of java.security.cert.Certificate in project robovm by robovm.

the class CertificateTest method testVerifyMD5.

public void testVerifyMD5() throws Exception {
    Provider[] providers = Security.getProviders("CertificateFactory.X509");
    for (Provider provider : providers) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509", provider);
        Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(selfSignedCertMD5.getBytes()));
        certificate.verify(certificate.getPublicKey());
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateFactory(java.security.cert.CertificateFactory) Provider(java.security.Provider) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 62 with Certificate

use of java.security.cert.Certificate 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)

Example 63 with Certificate

use of java.security.cert.Certificate in project robovm by robovm.

the class TestKeyStore method dump.

/**
     * Dump a key store for debugging.
     */
public static void dump(String context, KeyStore keyStore, char[] keyPassword) throws KeyStoreException, NoSuchAlgorithmException {
    PrintStream out = System.out;
    out.println("context=" + context);
    out.println("\tkeyStore=" + keyStore);
    out.println("\tkeyStore.type=" + keyStore.getType());
    out.println("\tkeyStore.provider=" + keyStore.getProvider());
    out.println("\tkeyPassword=" + ((keyPassword == null) ? null : new String(keyPassword)));
    out.println("\tsize=" + keyStore.size());
    for (String alias : Collections.list(keyStore.aliases())) {
        out.println("alias=" + alias);
        out.println("\tcreationDate=" + keyStore.getCreationDate(alias));
        if (keyStore.isCertificateEntry(alias)) {
            out.println("\tcertificate:");
            out.println("==========================================");
            out.println(keyStore.getCertificate(alias));
            out.println("==========================================");
            continue;
        }
        if (keyStore.isKeyEntry(alias)) {
            out.println("\tkey:");
            out.println("==========================================");
            String key;
            try {
                key = ("Key retrieved using password\n" + keyStore.getKey(alias, keyPassword));
            } catch (UnrecoverableKeyException e1) {
                try {
                    key = ("Key retrieved without password\n" + keyStore.getKey(alias, null));
                } catch (UnrecoverableKeyException e2) {
                    key = "Key could not be retrieved";
                }
            }
            out.println(key);
            out.println("==========================================");
            Certificate[] chain = keyStore.getCertificateChain(alias);
            if (chain == null) {
                out.println("No certificate chain associated with key");
                out.println("==========================================");
            } else {
                for (int i = 0; i < chain.length; i++) {
                    out.println("Certificate chain element #" + i);
                    out.println(chain[i]);
                    out.println("==========================================");
                }
            }
            continue;
        }
        out.println("\tunknown entry type");
    }
}
Also used : PrintStream(java.io.PrintStream) UnrecoverableKeyException(java.security.UnrecoverableKeyException) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 64 with Certificate

use of java.security.cert.Certificate in project robovm by robovm.

the class TestKeyStore method issuer.

/**
     * Return the issuing CA certificate of the given
     * certificate. Throws IllegalStateException if there are are more
     * or less than one.
     */
public static Certificate issuer(KeyStore keyStore, Certificate c) throws Exception {
    if (!(c instanceof X509Certificate)) {
        throw new IllegalStateException("issuer requires an X509Certificate, found " + c);
    }
    X509Certificate cert = (X509Certificate) c;
    Certificate found = null;
    for (String alias : Collections.list(keyStore.aliases())) {
        if (!keyStore.entryInstanceOf(alias, TrustedCertificateEntry.class)) {
            continue;
        }
        TrustedCertificateEntry certificateEntry = (TrustedCertificateEntry) keyStore.getEntry(alias, null);
        Certificate certificate = certificateEntry.getTrustedCertificate();
        if (!(certificate instanceof X509Certificate)) {
            continue;
        }
        X509Certificate x = (X509Certificate) certificate;
        if (!cert.getIssuerDN().equals(x.getSubjectDN())) {
            continue;
        }
        if (found != null) {
            throw new IllegalStateException("KeyStore has more than one issuing CA for " + cert + "\nfirst: " + found + "\nsecond: " + certificate);
        }
        found = certificate;
    }
    if (found == null) {
        throw new IllegalStateException("KeyStore contained no issuing CA for " + cert);
    }
    return found;
}
Also used : DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) TrustedCertificateEntry(java.security.KeyStore.TrustedCertificateEntry)

Example 65 with Certificate

use of java.security.cert.Certificate in project robovm by robovm.

the class CertPathBuilderTestPKIX method validateCertPath.

@Override
public void validateCertPath(CertPath path) {
    List<? extends Certificate> certificates = path.getCertificates();
    Certificate certificate = certificates.get(0);
    assertEquals("unexpected certificate type", "X.509", certificate.getType());
    X509Certificate x509Certificate = (X509Certificate) certificate;
    X500Principal subjectX500Principal = x509Certificate.getSubjectX500Principal();
    X500Principal expectedPrincipal = new X500Principal("CN=Android CTS, " + "OU=Android, O=Android, L=Android, ST=Android, C=AN");
    assertEquals("unexpected principal", expectedPrincipal, subjectX500Principal);
}
Also used : X500Principal(javax.security.auth.x500.X500Principal) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

Certificate (java.security.cert.Certificate)723 X509Certificate (java.security.cert.X509Certificate)469 CertificateFactory (java.security.cert.CertificateFactory)272 ByteArrayInputStream (java.io.ByteArrayInputStream)237 KeyStore (java.security.KeyStore)133 PrivateKey (java.security.PrivateKey)132 IOException (java.io.IOException)106 CertificateException (java.security.cert.CertificateException)102 KeyFactory (java.security.KeyFactory)89 KeyStoreException (java.security.KeyStoreException)88 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)72 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)69 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)63 ArrayList (java.util.ArrayList)63 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)56 Entry (java.security.KeyStore.Entry)53 PublicKey (java.security.PublicKey)48 InputStream (java.io.InputStream)40 FileInputStream (java.io.FileInputStream)39 Key (java.security.Key)36