Search in sources :

Example 11 with X500Principal

use of javax.security.auth.x500.X500Principal in project robovm by robovm.

the class ClientHandshakeImpl method processServerHelloDone.

/**
     * Processes ServerHelloDone: makes verification of the server messages; sends
     * client messages, computers masterSecret, sends ChangeCipherSpec
     */
void processServerHelloDone() {
    PrivateKey clientKey = null;
    if (serverCert != null) {
        if (session.cipherSuite.isAnonymous()) {
            unexpectedMessage();
            return;
        }
        verifyServerCert();
    } else {
        if (!session.cipherSuite.isAnonymous()) {
            unexpectedMessage();
            return;
        }
    }
    // Client certificate
    if (certificateRequest != null) {
        X509Certificate[] certs = null;
        // obtain certificates from key manager
        String alias = null;
        String[] certTypes = certificateRequest.getTypesAsString();
        X500Principal[] issuers = certificateRequest.certificate_authorities;
        X509KeyManager km = parameters.getKeyManager();
        if (km instanceof X509ExtendedKeyManager) {
            X509ExtendedKeyManager ekm = (X509ExtendedKeyManager) km;
            if (this.socketOwner != null) {
                alias = ekm.chooseClientAlias(certTypes, issuers, this.socketOwner);
            } else {
                alias = ekm.chooseEngineClientAlias(certTypes, issuers, this.engineOwner);
            }
            if (alias != null) {
                certs = ekm.getCertificateChain(alias);
            }
        } else {
            alias = km.chooseClientAlias(certTypes, issuers, this.socketOwner);
            if (alias != null) {
                certs = km.getCertificateChain(alias);
            }
        }
        session.localCertificates = certs;
        clientCert = new CertificateMessage(certs);
        clientKey = km.getPrivateKey(alias);
        send(clientCert);
    }
    // Client key exchange
    if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
        // RSA encrypted premaster secret message
        Cipher c;
        try {
            c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            if (serverKeyExchange != null) {
                if (!session.cipherSuite.isAnonymous()) {
                    DigitalSignature ds = new DigitalSignature(serverCert.getAuthType());
                    ds.init(serverCert.certs[0]);
                    ds.update(clientHello.getRandom());
                    ds.update(serverHello.getRandom());
                    if (!serverKeyExchange.verifySignature(ds)) {
                        fatalAlert(AlertProtocol.DECRYPT_ERROR, "Cannot verify RSA params");
                        return;
                    }
                }
                c.init(Cipher.WRAP_MODE, serverKeyExchange.getRSAPublicKey());
            } else {
                c.init(Cipher.WRAP_MODE, serverCert.certs[0]);
            }
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
            return;
        }
        preMasterSecret = new byte[48];
        parameters.getSecureRandom().nextBytes(preMasterSecret);
        System.arraycopy(clientHello.client_version, 0, preMasterSecret, 0, 2);
        try {
            clientKeyExchange = new ClientKeyExchange(c.wrap(new SecretKeySpec(preMasterSecret, "preMasterSecret")), serverHello.server_version[1] == 1);
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
            return;
        }
    } else if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS_EXPORT || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA_EXPORT || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon_EXPORT) {
        /*
             * All other key exchanges should have had a DH key communicated via
             * ServerKeyExchange beforehand.
             */
        if (serverKeyExchange == null) {
            fatalAlert(AlertProtocol.UNEXPECTED_MESSAGE, "Expected ServerKeyExchange");
            return;
        }
        if (session.cipherSuite.isAnonymous() != serverKeyExchange.isAnonymous()) {
            fatalAlert(AlertProtocol.DECRYPT_ERROR, "Wrong type in ServerKeyExchange");
            return;
        }
        try {
            if (!session.cipherSuite.isAnonymous()) {
                DigitalSignature ds = new DigitalSignature(serverCert.getAuthType());
                ds.init(serverCert.certs[0]);
                ds.update(clientHello.getRandom());
                ds.update(serverHello.getRandom());
                if (!serverKeyExchange.verifySignature(ds)) {
                    fatalAlert(AlertProtocol.DECRYPT_ERROR, "Cannot verify DH params");
                    return;
                }
            }
            KeyFactory kf = KeyFactory.getInstance("DH");
            KeyAgreement agreement = KeyAgreement.getInstance("DH");
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
            PublicKey serverDhPublic = kf.generatePublic(new DHPublicKeySpec(serverKeyExchange.par3, serverKeyExchange.par1, serverKeyExchange.par2));
            DHParameterSpec spec = new DHParameterSpec(serverKeyExchange.par1, serverKeyExchange.par2);
            kpg.initialize(spec);
            KeyPair kp = kpg.generateKeyPair();
            DHPublicKey pubDhKey = (DHPublicKey) kp.getPublic();
            clientKeyExchange = new ClientKeyExchange(pubDhKey.getY());
            PrivateKey privDhKey = kp.getPrivate();
            agreement.init(privDhKey);
            agreement.doPhase(serverDhPublic, true);
            preMasterSecret = agreement.generateSecret();
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
            return;
        }
    } else {
        fatalAlert(AlertProtocol.DECRYPT_ERROR, "Unsupported handshake type");
        return;
    }
    if (clientKeyExchange != null) {
        send(clientKeyExchange);
    }
    computerMasterSecret();
    // fixed DH parameters
    if (clientCert != null && clientCert.certs.length > 0 && !clientKeyExchange.isEmpty()) {
        // Certificate verify
        String authType = clientKey.getAlgorithm();
        DigitalSignature ds = new DigitalSignature(authType);
        ds.init(clientKey);
        if ("RSA".equals(authType)) {
            ds.setMD5(io_stream.getDigestMD5());
            ds.setSHA(io_stream.getDigestSHA());
        } else if ("DSA".equals(authType)) {
            ds.setSHA(io_stream.getDigestSHA());
        // The Signature should be empty in case of anonymous signature algorithm:
        // } else if ("DH".equals(authType)) {
        }
        certificateVerify = new CertificateVerify(ds.sign());
        send(certificateVerify);
    }
    sendChangeCipherSpec();
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) PublicKey(java.security.PublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) X509ExtendedKeyManager(javax.net.ssl.X509ExtendedKeyManager) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) X509KeyManager(javax.net.ssl.X509KeyManager) X500Principal(javax.security.auth.x500.X500Principal) Cipher(javax.crypto.Cipher) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory)

Example 12 with X500Principal

use of javax.security.auth.x500.X500Principal in project robovm by robovm.

the class NativeCryptoTest method initCerts.

/**
     * Lazily create shared test certificates.
     */
private static synchronized void initCerts() {
    if (SERVER_PRIVATE_KEY != null) {
        return;
    }
    try {
        PrivateKeyEntry serverPrivateKeyEntry = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
        SERVER_PRIVATE_KEY = OpenSSLKey.fromPrivateKey(serverPrivateKeyEntry.getPrivateKey());
        SERVER_CERTIFICATES = NativeCrypto.encodeCertificates(serverPrivateKeyEntry.getCertificateChain());
        PrivateKeyEntry clientPrivateKeyEntry = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA");
        CLIENT_PRIVATE_KEY = OpenSSLKey.fromPrivateKey(clientPrivateKeyEntry.getPrivateKey());
        CLIENT_CERTIFICATES = NativeCrypto.encodeCertificates(clientPrivateKeyEntry.getCertificateChain());
        KeyStore ks = TestKeyStore.getClient().keyStore;
        String caCertAlias = ks.aliases().nextElement();
        X509Certificate certificate = (X509Certificate) ks.getCertificate(caCertAlias);
        X500Principal principal = certificate.getIssuerX500Principal();
        CA_PRINCIPALS = new byte[][] { principal.getEncoded() };
        initChannelIdKey();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : X500Principal(javax.security.auth.x500.X500Principal) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) TestKeyStore(libcore.java.security.TestKeyStore) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) SocketTimeoutException(java.net.SocketTimeoutException) SSLProtocolException(javax.net.ssl.SSLProtocolException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) SSLException(javax.net.ssl.SSLException)

Example 13 with X500Principal

use of javax.security.auth.x500.X500Principal in project robovm by robovm.

the class TrustedCertificateStoreTest method alias.

/**
     * format a certificate alias
     */
private static String alias(boolean user, X509Certificate x, int index) {
    String prefix = user ? "user:" : "system:";
    X500Principal subject = x.getSubjectX500Principal();
    int intHash = NativeCrypto.X509_NAME_hash_old(subject);
    String strHash = IntegralToString.intToHexString(intHash, false, 8);
    return prefix + strHash + '.' + index;
}
Also used : X500Principal(javax.security.auth.x500.X500Principal)

Example 14 with X500Principal

use of javax.security.auth.x500.X500Principal in project robovm by robovm.

the class RFC3280CertPathUtilities method processCertBC.

protected static void processCertBC(CertPath certPath, int index, PKIXNameConstraintValidator nameConstraintValidator) throws CertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    int n = certs.size();
    // i as defined in the algorithm description
    int i = n - index;
    //
    if (!(CertPathValidatorUtilities.isSelfIssued(cert) && (i < n))) {
        X500Principal principal = CertPathValidatorUtilities.getSubjectPrincipal(cert);
        ASN1InputStream aIn = new ASN1InputStream(principal.getEncoded());
        ASN1Sequence dns;
        try {
            dns = DERSequence.getInstance(aIn.readObject());
        } catch (Exception e) {
            throw new CertPathValidatorException("Exception extracting subject name when checking subtrees.", e, certPath, index);
        }
        try {
            nameConstraintValidator.checkPermittedDN(dns);
            nameConstraintValidator.checkExcludedDN(dns);
        } catch (PKIXNameConstraintValidatorException e) {
            throw new CertPathValidatorException("Subtree check for certificate subject failed.", e, certPath, index);
        }
        GeneralNames altName = null;
        try {
            altName = GeneralNames.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME));
        } catch (Exception e) {
            throw new CertPathValidatorException("Subject alternative name extension could not be decoded.", e, certPath, index);
        }
        Vector emails = new X509Name(dns).getValues(X509Name.EmailAddress);
        for (Enumeration e = emails.elements(); e.hasMoreElements(); ) {
            String email = (String) e.nextElement();
            GeneralName emailAsGeneralName = new GeneralName(GeneralName.rfc822Name, email);
            try {
                nameConstraintValidator.checkPermitted(emailAsGeneralName);
                nameConstraintValidator.checkExcluded(emailAsGeneralName);
            } catch (PKIXNameConstraintValidatorException ex) {
                throw new CertPathValidatorException("Subtree check for certificate subject alternative email failed.", ex, certPath, index);
            }
        }
        if (altName != null) {
            GeneralName[] genNames = null;
            try {
                genNames = altName.getNames();
            } catch (Exception e) {
                throw new CertPathValidatorException("Subject alternative name contents could not be decoded.", e, certPath, index);
            }
            for (int j = 0; j < genNames.length; j++) {
                try {
                    nameConstraintValidator.checkPermitted(genNames[j]);
                    nameConstraintValidator.checkExcluded(genNames[j]);
                } catch (PKIXNameConstraintValidatorException e) {
                    throw new CertPathValidatorException("Subtree check for certificate subject alternative name failed.", e, certPath, index);
                }
            }
        }
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) X509Certificate(java.security.cert.X509Certificate) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) X509Name(org.bouncycastle.asn1.x509.X509Name) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) List(java.util.List) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector)

Example 15 with X500Principal

use of javax.security.auth.x500.X500Principal in project robovm by robovm.

the class AttributeCertificateIssuer method getPrincipals.

/**
     * Return any principal objects inside the attribute certificate issuer
     * object.
     * 
     * @return an array of Principal objects (usually X500Principal)
     */
public Principal[] getPrincipals() {
    Object[] p = this.getNames();
    List l = new ArrayList();
    for (int i = 0; i != p.length; i++) {
        if (p[i] instanceof Principal) {
            l.add(p[i]);
        }
    }
    return (Principal[]) l.toArray(new Principal[l.size()]);
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) X509Principal(org.bouncycastle.jce.X509Principal) X500Principal(javax.security.auth.x500.X500Principal) Principal(java.security.Principal)

Aggregations

X500Principal (javax.security.auth.x500.X500Principal)246 X509Certificate (java.security.cert.X509Certificate)68 IOException (java.io.IOException)52 ArrayList (java.util.ArrayList)39 List (java.util.List)25 Principal (java.security.Principal)21 PublicKey (java.security.PublicKey)21 TrustAnchor (java.security.cert.TrustAnchor)21 Certificate (java.security.cert.Certificate)20 X509CertSelector (java.security.cert.X509CertSelector)16 HashMap (java.util.HashMap)16 BigInteger (java.math.BigInteger)15 KeyPair (java.security.KeyPair)15 HashSet (java.util.HashSet)14 Test (org.junit.Test)14 KeyPairGenerator (java.security.KeyPairGenerator)13 CertPathValidatorException (java.security.cert.CertPathValidatorException)13 CertificateException (java.security.cert.CertificateException)13 GeneralSecurityException (java.security.GeneralSecurityException)12 CertificateParsingException (java.security.cert.CertificateParsingException)12