Search in sources :

Example 66 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project OpenAttestation by OpenAttestation.

the class CertificateRepository method create.

@Override
public //    @RequiresPermissions("tag_certificates:create") 
void create(Certificate item) {
    log.debug("Certificate:Create - Got request to create a new Certificate {}.", item.getId().toString());
    CertificateLocator locator = new CertificateLocator();
    locator.id = item.getId();
    try (CertificateDAO dao = TagJdbi.certificateDao()) {
        Certificate newCert = dao.findById(item.getId());
        if (newCert == null) {
            newCert = Certificate.valueOf(item.getCertificate());
            dao.insert(item.getId(), newCert.getCertificate(), newCert.getSha1().toHexString(), newCert.getSha256().toHexString(), newCert.getSubject(), newCert.getIssuer(), newCert.getNotBefore(), newCert.getNotAfter());
            log.debug("Certificate:Create - Created the Certificate {} successfully.", item.getId().toString());
        } else {
            log.error("Certificate:Create - Certificate {} will not be created since a duplicate Certificate already exists.", item.getId().toString());
            throw new RepositoryCreateConflictException(locator);
        }
    } catch (RepositoryException re) {
        throw re;
    } catch (Exception ex) {
        log.error("Certificate:Create - Error during certificate creation.", ex);
        throw new RepositoryCreateException(ex, locator);
    }
    //Store tag values from Certificate
    try {
        log.info("Tags from certificate will now be stored");
        KvAttributeRepository repository = new KvAttributeRepository();
        KvAttribute kvAttrib = new KvAttribute();
        if (kvAttrib == null || repository == null)
            log.debug("kvAttrib or repository Obj is null, unable to store certificate tags");
        else {
            List<Attribute> certAttributes = X509AttributeCertificate.valueOf(item.getCertificate()).getAttribute();
            for (Attribute attr : certAttributes) {
                for (ASN1Encodable value : attr.getAttributeValues()) {
                    if (attr.getAttrType().toString().equals(UTF8NameValueMicroformat.OID)) {
                        UTF8NameValueMicroformat microformat = new UTF8NameValueMicroformat(DERUTF8String.getInstance(value));
                        // Check if that tag with same value already exists
                        KvAttributeFilterCriteria criteria = new KvAttributeFilterCriteria();
                        criteria.nameEqualTo = microformat.getName();
                        criteria.valueEqualTo = microformat.getValue();
                        KvAttributeCollection results = repository.search(criteria);
                        if (results.getDocuments().isEmpty()) {
                            kvAttrib.setId(new UUID());
                            kvAttrib.setName(microformat.getName());
                            kvAttrib.setValue(microformat.getValue());
                            repository.create(kvAttrib);
                        } else
                            log.debug("Tag with Name:{} & Value:{} is already stored.", microformat.getName(), microformat.getValue());
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Certificate:Create - Error during attribute scan", e);
    }
}
Also used : CertificateLocator(com.intel.mtwilson.datatypes.CertificateLocator) CertificateDAO(com.intel.mtwilson.tag.dao.jdbi.CertificateDAO) KvAttribute(com.intel.mtwilson.datatypes.KvAttribute) Attribute(org.bouncycastle.asn1.x509.Attribute) KvAttribute(com.intel.mtwilson.datatypes.KvAttribute) RepositoryException(com.intel.mtwilson.tag.repository.RepositoryException) RepositoryCreateConflictException(com.intel.mtwilson.tag.repository.RepositoryCreateConflictException) RepositoryCreateException(com.intel.mtwilson.tag.repository.RepositoryCreateException) RepositoryDeleteException(com.intel.mtwilson.tag.repository.RepositoryDeleteException) RepositoryStoreException(com.intel.mtwilson.tag.repository.RepositoryStoreException) RepositoryStoreConflictException(com.intel.mtwilson.tag.repository.RepositoryStoreConflictException) RepositoryRetrieveException(com.intel.mtwilson.tag.repository.RepositoryRetrieveException) RepositoryException(com.intel.mtwilson.tag.repository.RepositoryException) RepositorySearchException(com.intel.mtwilson.tag.repository.RepositorySearchException) RepositoryCreateConflictException(com.intel.mtwilson.tag.repository.RepositoryCreateConflictException) KvAttributeCollection(com.intel.mtwilson.datatypes.KvAttributeCollection) KvAttributeRepository(com.intel.mtwilson.tag.repository.KvAttributeRepository) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) KvAttributeFilterCriteria(com.intel.mtwilson.datatypes.KvAttributeFilterCriteria) UUID(com.intel.mtwilson.util.io.UUID) UTF8NameValueMicroformat(com.intel.mtwilson.datatypes.UTF8NameValueMicroformat) Certificate(com.intel.mtwilson.datatypes.Certificate) X509AttributeCertificate(com.intel.mtwilson.datatypes.X509AttributeCertificate) RepositoryCreateException(com.intel.mtwilson.tag.repository.RepositoryCreateException)

Example 67 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project OpenAttestation by OpenAttestation.

the class ProvisionTagCertificate method certificateAttributesEqual.

//    
//    /**
//     * Check that the attributes in the certificate are the same as the attributes in the given selection.
//     * The order is not considered so they do not have to be in the same order.
//     * 
//     * The given selection must have inline attributes (not requiring any lookup by id or name).
//     * 
//     * @return true if the attribute certificate has exactly the same attributes as in the given selection
//     */
protected boolean certificateAttributesEqual(X509AttributeCertificate certificate, SelectionType selection) throws IOException {
    List<Attribute> certAttributes = certificate.getAttribute();
    // initialized with all false, later we mark individual elements true if they are found within the given selection, so that if any are left false at the end we know that there are attributes in the cert that were not in the selection
    boolean[] certAttrMatch = new boolean[certAttributes.size()];
    // for every attribute in the selection, check if it's present in the certificate 
    for (AttributeType xmlAttribute : selection.getAttribute()) {
        X509AttrBuilder.Attribute oidAndValue = Util.toAttributeOidValue(xmlAttribute);
        // look through the certificate for same oid and value
        boolean found = false;
        for (int i = 0; i < certAttrMatch.length; i++) {
            if (Arrays.equals(certAttributes.get(i).getAttrType().getDEREncoded(), oidAndValue.oid.getDEREncoded())) {
                if (Arrays.equals(certAttributes.get(i).getAttributeValues()[0].getDEREncoded(), oidAndValue.value.getDEREncoded())) {
                    certAttrMatch[i] = true;
                    found = true;
                }
            }
        }
        if (!found) {
            log.debug("Certificate does not have attribute oid {} and value {}", Hex.encodeHexString(oidAndValue.oid.getDEREncoded()), Hex.encodeHexString(oidAndValue.value.getDEREncoded()));
            return false;
        }
    }
    // check if the certificate has any attributes that are not in the selection 
    for (int i = 0; i < certAttrMatch.length; i++) {
        if (!certAttrMatch[i]) {
            log.debug("Selection does not have attribute oid {} and value {}", Hex.encodeHexString(certAttributes.get(i).getAttrType().getDEREncoded()), Hex.encodeHexString(certAttributes.get(i).getAttributeValues()[0].getDEREncoded()));
            return false;
        }
    }
    // certificate and selection have same set of attribute (oid,value) pairs
    return true;
}
Also used : Attribute(org.bouncycastle.asn1.x509.Attribute) AttributeType(com.intel.mtwilson.tag.selection.xml.AttributeType) X509AttrBuilder(com.intel.mtwilson.tag.common.X509AttrBuilder)

Example 68 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerBuilder     IssuerDN builder
     * @param subjectBuilder    SubjectDN builder
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new //
    JcaX509v3CertificateBuilder(//
    issuerDN, //
    serial, //
    new Date(), //
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
    subjectDN, //
    pubKey);
    // add subjectAlternativeName extension
    boolean critical = subjectDN.getRDNs().length == 0;
    ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertException(org.bouncycastle.cert.CertException) Date(java.util.Date) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 69 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method processCRLF.

/**
     * Obtain and validate the certification path for the complete CRL issuer.
     * If a key usage extension is present in the CRL issuer's certificate,
     * verify that the cRLSign bit is set.
     *
     * @param crl                CRL which contains revocation information for the certificate
     *                           <code>cert</code>.
     * @param cert               The attribute certificate or certificate to check if it is
     *                           revoked.
     * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
     * @param defaultCRLSignKey  The public key of the issuer certificate
     *                           <code>defaultCRLSignCert</code>.
     * @param paramsPKIX         paramsPKIX PKIX parameters.
     * @param certPathCerts      The certificates on the certification path.
     * @return A <code>Set</code> with all keys of possible CRL issuer
     *         certificates.
     * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
     *                            some error occurs.
     */
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
    // (f)
    // get issuer from CRL
    X509CertStoreSelector selector = new X509CertStoreSelector();
    try {
        byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
        selector.setSubject(issuerPrincipal);
    } catch (IOException e) {
        throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
    }
    // get CRL signing certs
    Collection coll;
    try {
        coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
    } catch (AnnotatedException e) {
        throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
    }
    coll.add(defaultCRLSignCert);
    Iterator cert_it = coll.iterator();
    List validCerts = new ArrayList();
    List validKeys = new ArrayList();
    while (cert_it.hasNext()) {
        X509Certificate signingCert = (X509Certificate) cert_it.next();
        /*
             * CA of the certificate, for which this CRL is checked, has also
             * signed CRL, so skip the path validation, because is already done
             */
        if (signingCert.equals(defaultCRLSignCert)) {
            validCerts.add(signingCert);
            validKeys.add(defaultCRLSignKey);
            continue;
        }
        try {
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
            selector = new X509CertStoreSelector();
            selector.setCertificate(signingCert);
            ExtendedPKIXParameters temp = (ExtendedPKIXParameters) paramsPKIX.clone();
            temp.setTargetCertConstraints(selector);
            ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters.getInstance(temp);
            /*
                 * if signingCert is placed not higher on the cert path a
                 * dependency loop results. CRL for cert is checked, but
                 * signingCert is needed for checking the CRL which is dependent
                 * on checking cert because it is higher in the cert path and so
                 * signing signingCert transitively. so, revocation is disabled,
                 * forgery attacks of the CRL are detected in this outer loop
                 * for all other it must be enabled to prevent forgery attacks
                 */
            if (certPathCerts.contains(signingCert)) {
                params.setRevocationEnabled(false);
            } else {
                params.setRevocationEnabled(true);
            }
            List certs = builder.build(params).getCertPath().getCertificates();
            validCerts.add(signingCert);
            validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
        } catch (CertPathBuilderException e) {
            throw new AnnotatedException("Internal error.", e);
        } catch (CertPathValidatorException e) {
            throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    Set checkKeys = new HashSet();
    AnnotatedException lastException = null;
    for (int i = 0; i < validCerts.size(); i++) {
        X509Certificate signCert = (X509Certificate) validCerts.get(i);
        boolean[] keyusage = signCert.getKeyUsage();
        if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
            lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
        } else {
            checkKeys.add(validKeys.get(i));
        }
    }
    if (checkKeys.isEmpty() && lastException == null) {
        throw new AnnotatedException("Cannot find a valid issuer certificate.");
    }
    if (checkKeys.isEmpty() && lastException != null) {
        throw lastException;
    }
    return checkKeys;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ExtendedPKIXBuilderParameters(org.bouncycastle.x509.ExtendedPKIXBuilderParameters) X509CertStoreSelector(org.bouncycastle.x509.X509CertStoreSelector) ArrayList(java.util.ArrayList) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) 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) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) CertPathBuilder(java.security.cert.CertPathBuilder) HashSet(java.util.HashSet)

Example 70 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project XobotOS by xamarin.

the class JDKPKCS12KeyStore method engineGetCertificateChain.

public Certificate[] engineGetCertificateChain(String alias) {
    if (alias == null) {
        throw new IllegalArgumentException("null alias passed to getCertificateChain.");
    }
    if (!engineIsKeyEntry(alias)) {
        return null;
    }
    Certificate c = engineGetCertificate(alias);
    if (c != null) {
        Vector cs = new Vector();
        while (c != null) {
            X509Certificate x509c = (X509Certificate) c;
            Certificate nextC = null;
            byte[] bytes = x509c.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
            if (bytes != null) {
                try {
                    ASN1InputStream aIn = new ASN1InputStream(bytes);
                    byte[] authBytes = ((ASN1OctetString) aIn.readObject()).getOctets();
                    aIn = new ASN1InputStream(authBytes);
                    AuthorityKeyIdentifier id = new AuthorityKeyIdentifier((ASN1Sequence) aIn.readObject());
                    if (id.getKeyIdentifier() != null) {
                        nextC = (Certificate) chainCerts.get(new CertId(id.getKeyIdentifier()));
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e.toString());
                }
            }
            if (nextC == null) {
                //
                // no authority key id, try the Issuer DN
                //
                Principal i = x509c.getIssuerDN();
                Principal s = x509c.getSubjectDN();
                if (!i.equals(s)) {
                    Enumeration e = chainCerts.keys();
                    while (e.hasMoreElements()) {
                        X509Certificate crt = (X509Certificate) chainCerts.get(e.nextElement());
                        Principal sub = crt.getSubjectDN();
                        if (sub.equals(i)) {
                            try {
                                x509c.verify(crt.getPublicKey());
                                nextC = crt;
                                break;
                            } catch (Exception ex) {
                            // continue
                            }
                        }
                    }
                }
            }
            cs.addElement(c);
            if (// self signed - end of the chain
            nextC != c) {
                c = nextC;
            } else {
                c = null;
            }
        }
        Certificate[] certChain = new Certificate[cs.size()];
        for (int i = 0; i != certChain.length; i++) {
            certChain[i] = (Certificate) cs.elementAt(i);
        }
        return certChain;
    }
    return null;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

IOException (java.io.IOException)242 X509Certificate (java.security.cert.X509Certificate)216 Date (java.util.Date)133 X500Name (org.bouncycastle.asn1.x500.X500Name)133 BigInteger (java.math.BigInteger)120 ContentSigner (org.bouncycastle.operator.ContentSigner)102 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)101 GeneralName (org.bouncycastle.asn1.x509.GeneralName)100 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)96 CertificateException (java.security.cert.CertificateException)95 ArrayList (java.util.ArrayList)90 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)85 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)82 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)78 GeneralSecurityException (java.security.GeneralSecurityException)69 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)62 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)62 Extension (org.bouncycastle.asn1.x509.Extension)61 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)60 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)59