Search in sources :

Example 6 with X500Principal

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

the class CertPathValidatorUtilities method getCertStatus.

protected static void getCertStatus(Date validDate, X509CRL crl, Object cert, CertStatus certStatus) throws AnnotatedException {
    X509CRLEntry crl_entry = null;
    boolean isIndirect;
    try {
        isIndirect = X509CRLObject.isIndirectCRL(crl);
    } catch (CRLException exception) {
        throw new AnnotatedException("Failed check for indirect CRL.", exception);
    }
    if (isIndirect) {
        crl_entry = crl.getRevokedCertificate(getSerialNumber(cert));
        if (crl_entry == null) {
            return;
        }
        X500Principal certIssuer = crl_entry.getCertificateIssuer();
        if (certIssuer == null) {
            certIssuer = getIssuerPrincipal(crl);
        }
        if (!getEncodedIssuerPrincipal(cert).equals(certIssuer)) {
            return;
        }
    } else if (!getEncodedIssuerPrincipal(cert).equals(getIssuerPrincipal(crl))) {
        // not for our issuer, ignore
        return;
    } else {
        crl_entry = crl.getRevokedCertificate(getSerialNumber(cert));
        if (crl_entry == null) {
            return;
        }
    }
    DEREnumerated reasonCode = null;
    if (crl_entry.hasExtensions()) {
        try {
            reasonCode = DEREnumerated.getInstance(CertPathValidatorUtilities.getExtensionValue(crl_entry, X509Extension.reasonCode.getId()));
        } catch (Exception e) {
            throw new AnnotatedException("Reason code CRL entry extension could not be decoded.", e);
        }
    }
    // unspecified
    if (!(validDate.getTime() < crl_entry.getRevocationDate().getTime()) || reasonCode == null || reasonCode.getValue().intValue() == 0 || reasonCode.getValue().intValue() == 1 || reasonCode.getValue().intValue() == 2 || reasonCode.getValue().intValue() == 8) {
        // (i) or (j) (1)
        if (reasonCode != null) {
            certStatus.setCertStatus(reasonCode.getValue().intValue());
        } else // (i) or (j) (2)
        {
            certStatus.setCertStatus(CRLReason.unspecified);
        }
        certStatus.setRevocationDate(crl_entry.getRevocationDate());
    }
}
Also used : X509CRLEntry(java.security.cert.X509CRLEntry) DEREnumerated(org.bouncycastle.asn1.DEREnumerated) X500Principal(javax.security.auth.x500.X500Principal) CRLException(java.security.cert.CRLException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ParseException(java.text.ParseException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertStoreException(java.security.cert.CertStoreException) CRLException(java.security.cert.CRLException) CertificateParsingException(java.security.cert.CertificateParsingException) StoreException(org.bouncycastle.util.StoreException) IOException(java.io.IOException)

Example 7 with X500Principal

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

the class CertPathValidatorUtilities method getCRLIssuersFromDistributionPoint.

/**
     * Add the CRL issuers from the cRLIssuer field of the distribution point or
     * from the certificate if not given to the issuer criterion of the
     * <code>selector</code>.
     * <p/>
     * The <code>issuerPrincipals</code> are a collection with a single
     * <code>X500Principal</code> for <code>X509Certificate</code>s. For
     * {@link X509AttributeCertificate}s the issuer may contain more than one
     * <code>X500Principal</code>.
     *
     * @param dp               The distribution point.
     * @param issuerPrincipals The issuers of the certificate or attribute
     *                         certificate which contains the distribution point.
     * @param selector         The CRL selector.
     * @param pkixParams       The PKIX parameters containing the cert stores.
     * @throws AnnotatedException if an exception occurs while processing.
     * @throws ClassCastException if <code>issuerPrincipals</code> does not
     * contain only <code>X500Principal</code>s.
     */
protected static void getCRLIssuersFromDistributionPoint(DistributionPoint dp, Collection issuerPrincipals, X509CRLSelector selector, ExtendedPKIXParameters pkixParams) throws AnnotatedException {
    List issuers = new ArrayList();
    // indirect CRL
    if (dp.getCRLIssuer() != null) {
        GeneralName[] genNames = dp.getCRLIssuer().getNames();
        // look for a DN
        for (int j = 0; j < genNames.length; j++) {
            if (genNames[j].getTagNo() == GeneralName.directoryName) {
                try {
                    issuers.add(new X500Principal(genNames[j].getName().toASN1Primitive().getEncoded()));
                } catch (IOException e) {
                    throw new AnnotatedException("CRL issuer information from distribution point cannot be decoded.", e);
                }
            }
        }
    } else {
        /*
             * certificate issuer is CRL issuer, distributionPoint field MUST be
             * present.
             */
        if (dp.getDistributionPoint() == null) {
            throw new AnnotatedException("CRL issuer is omitted from distribution point but no distributionPoint field present.");
        }
        // add and check issuer principals
        for (Iterator it = issuerPrincipals.iterator(); it.hasNext(); ) {
            issuers.add((X500Principal) it.next());
        }
    }
    // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
    // distributionPoint
    //        if (dp.getDistributionPoint() != null)
    //        {
    //            // look for nameRelativeToCRLIssuer
    //            if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
    //            {
    //                // append fragment to issuer, only one
    //                // issuer can be there, if this is given
    //                if (issuers.size() != 1)
    //                {
    //                    throw new AnnotatedException(
    //                        "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
    //                }
    //                ASN1Encodable relName = dp.getDistributionPoint().getName();
    //                Iterator it = issuers.iterator();
    //                List issuersTemp = new ArrayList(issuers.size());
    //                while (it.hasNext())
    //                {
    //                    Enumeration e = null;
    //                    try
    //                    {
    //                        e = ASN1Sequence.getInstance(
    //                            new ASN1InputStream(((X500Principal) it.next())
    //                                .getEncoded()).readObject()).getObjects();
    //                    }
    //                    catch (IOException ex)
    //                    {
    //                        throw new AnnotatedException(
    //                            "Cannot decode CRL issuer information.", ex);
    //                    }
    //                    ASN1EncodableVector v = new ASN1EncodableVector();
    //                    while (e.hasMoreElements())
    //                    {
    //                        v.add((ASN1Encodable) e.nextElement());
    //                    }
    //                    v.add(relName);
    //                    issuersTemp.add(new X500Principal(new DERSequence(v)
    //                        .getDEREncoded()));
    //                }
    //                issuers.clear();
    //                issuers.addAll(issuersTemp);
    //            }
    //        }
    Iterator it = issuers.iterator();
    while (it.hasNext()) {
        try {
            selector.addIssuerName(((X500Principal) it.next()).getEncoded());
        } catch (IOException ex) {
            throw new AnnotatedException("Cannot decode CRL issuer information.", ex);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) X500Principal(javax.security.auth.x500.X500Principal) List(java.util.List) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint)

Example 8 with X500Principal

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

the class X509CertificateObject method getIssuerX500Principal.

public X500Principal getIssuerX500Principal() {
    try {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ASN1OutputStream aOut = new ASN1OutputStream(bOut);
        aOut.writeObject(c.getIssuer());
        return new X500Principal(bOut.toByteArray());
    } catch (IOException e) {
        throw new IllegalStateException("can't encode issuer DN");
    }
}
Also used : X500Principal(javax.security.auth.x500.X500Principal) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ASN1OutputStream(org.bouncycastle.asn1.ASN1OutputStream)

Example 9 with X500Principal

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

the class JarUtils method verifySignature.

/**
     * This method handle all the work with  PKCS7, ASN1 encoding, signature verifying,
     * and certification path building.
     * See also PKCS #7: Cryptographic Message Syntax Standard:
     * http://www.ietf.org/rfc/rfc2315.txt
     * @param signature - the input stream of signature file to be verified
     * @param signatureBlock - the input stream of corresponding signature block file
     * @return array of certificates used to verify the signature file
     * @throws IOException - if some errors occurs during reading from the stream
     * @throws GeneralSecurityException - if signature verification process fails
     */
public static Certificate[] verifySignature(InputStream signature, InputStream signatureBlock) throws IOException, GeneralSecurityException {
    BerInputStream bis = new BerInputStream(signatureBlock);
    ContentInfo info = (ContentInfo) ContentInfo.ASN1.decode(bis);
    SignedData signedData = info.getSignedData();
    if (signedData == null) {
        throw new IOException("No SignedData found");
    }
    Collection<org.apache.harmony.security.x509.Certificate> encCerts = signedData.getCertificates();
    if (encCerts.isEmpty()) {
        return null;
    }
    X509Certificate[] certs = new X509Certificate[encCerts.size()];
    int i = 0;
    for (org.apache.harmony.security.x509.Certificate encCert : encCerts) {
        certs[i++] = new X509CertImpl(encCert);
    }
    List<SignerInfo> sigInfos = signedData.getSignerInfos();
    SignerInfo sigInfo;
    if (!sigInfos.isEmpty()) {
        sigInfo = sigInfos.get(0);
    } else {
        return null;
    }
    // Issuer
    X500Principal issuer = sigInfo.getIssuer();
    // Certificate serial number
    BigInteger snum = sigInfo.getSerialNumber();
    // Locate the certificate
    int issuerSertIndex = 0;
    for (i = 0; i < certs.length; i++) {
        if (issuer.equals(certs[i].getIssuerDN()) && snum.equals(certs[i].getSerialNumber())) {
            issuerSertIndex = i;
            break;
        }
    }
    if (i == certs.length) {
        // No issuer certificate found
        return null;
    }
    if (certs[issuerSertIndex].hasUnsupportedCriticalExtension()) {
        throw new SecurityException("Can not recognize a critical extension");
    }
    // Get Signature instance
    final String daOid = sigInfo.getDigestAlgorithm();
    final String daName = sigInfo.getDigestAlgorithmName();
    final String deaOid = sigInfo.getDigestEncryptionAlgorithm();
    String alg = null;
    Signature sig = null;
    if (daOid != null && deaOid != null) {
        alg = daOid + "with" + deaOid;
        try {
            sig = Signature.getInstance(alg);
        } catch (NoSuchAlgorithmException e) {
        }
        // Try to convert to names instead of OID.
        if (sig == null) {
            final String deaName = sigInfo.getDigestEncryptionAlgorithmName();
            alg = daName + "with" + deaName;
            try {
                sig = Signature.getInstance(alg);
            } catch (NoSuchAlgorithmException e) {
            }
        }
    }
    /*
         * TODO figure out the case in which we'd only use digestAlgorithm and
         * add a test for it.
         */
    if (sig == null && daOid != null) {
        alg = daOid;
        try {
            sig = Signature.getInstance(alg);
        } catch (NoSuchAlgorithmException e) {
        }
        if (sig == null && daName != null) {
            alg = daName;
            try {
                sig = Signature.getInstance(alg);
            } catch (NoSuchAlgorithmException e) {
            }
        }
    }
    // We couldn't find a valid Signature type.
    if (sig == null) {
        return null;
    }
    sig.initVerify(certs[issuerSertIndex]);
    // If the authenticatedAttributes field of SignerInfo contains more than zero attributes,
    // compute the message digest on the ASN.1 DER encoding of the Attributes value.
    // Otherwise, compute the message digest on the data.
    List<AttributeTypeAndValue> atr = sigInfo.getAuthenticatedAttributes();
    byte[] sfBytes = new byte[signature.available()];
    signature.read(sfBytes);
    if (atr == null) {
        sig.update(sfBytes);
    } else {
        sig.update(sigInfo.getEncodedAuthenticatedAttributes());
        // If the authenticatedAttributes field contains the message-digest attribute,
        // verify that it equals the computed digest of the signature file
        byte[] existingDigest = null;
        for (AttributeTypeAndValue a : atr) {
            if (Arrays.equals(a.getType().getOid(), MESSAGE_DIGEST_OID)) {
                if (existingDigest != null) {
                    throw new SecurityException("Too many MessageDigest attributes");
                }
                Collection<?> entries = a.getValue().getValues(ASN1OctetString.getInstance());
                if (entries.size() != 1) {
                    throw new SecurityException("Too many values for MessageDigest attribute");
                }
                existingDigest = (byte[]) entries.iterator().next();
            }
        }
        // message digest entry.
        if (existingDigest == null) {
            throw new SecurityException("Missing MessageDigest in Authenticated Attributes");
        }
        MessageDigest md = null;
        if (daOid != null) {
            md = MessageDigest.getInstance(daOid);
        }
        if (md == null && daName != null) {
            md = MessageDigest.getInstance(daName);
        }
        if (md == null) {
            return null;
        }
        byte[] computedDigest = md.digest(sfBytes);
        if (!Arrays.equals(existingDigest, computedDigest)) {
            throw new SecurityException("Incorrect MD");
        }
    }
    if (!sig.verify(sigInfo.getEncryptedDigest())) {
        throw new SecurityException("Incorrect signature");
    }
    return createChain(certs[issuerSertIndex], certs);
}
Also used : ASN1OctetString(org.apache.harmony.security.asn1.ASN1OctetString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ContentInfo(org.apache.harmony.security.pkcs7.ContentInfo) X509CertImpl(org.apache.harmony.security.provider.cert.X509CertImpl) BerInputStream(org.apache.harmony.security.asn1.BerInputStream) MessageDigest(java.security.MessageDigest) SignedData(org.apache.harmony.security.pkcs7.SignedData) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) AttributeTypeAndValue(org.apache.harmony.security.x501.AttributeTypeAndValue) SignerInfo(org.apache.harmony.security.pkcs7.SignerInfo) Signature(java.security.Signature) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 10 with X500Principal

use of javax.security.auth.x500.X500Principal 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

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