Search in sources :

Example 1 with CertId

use of org.bouncycastle.asn1.crmf.CertId 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)

Example 2 with CertId

use of org.bouncycastle.asn1.crmf.CertId in project XobotOS by xamarin.

the class JDKPKCS12KeyStore method doStore.

private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) throws IOException {
    if (password == null) {
        throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
    }
    //
    // handle the key
    //
    ASN1EncodableVector keyS = new ASN1EncodableVector();
    Enumeration ks = keys.keys();
    while (ks.hasMoreElements()) {
        byte[] kSalt = new byte[SALT_SIZE];
        random.nextBytes(kSalt);
        String name = (String) ks.nextElement();
        PrivateKey privKey = (PrivateKey) keys.get(name);
        PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS);
        byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password);
        AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.getDERObject());
        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes);
        boolean attrSet = false;
        ASN1EncodableVector kName = new ASN1EncodableVector();
        if (privKey instanceof PKCS12BagAttributeCarrier) {
            PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) privKey;
            //
            // make sure we are using the local alias on store
            //
            DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
            if (nm == null || !nm.getString().equals(name)) {
                bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
            }
            //
            if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                Certificate ct = engineGetCertificate(name);
                bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey()));
            }
            Enumeration e = bagAttrs.getBagAttributeKeys();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                ASN1EncodableVector kSeq = new ASN1EncodableVector();
                kSeq.add(oid);
                kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                attrSet = true;
                kName.add(new DERSequence(kSeq));
            }
        }
        if (!attrSet) {
            //
            // set a default friendly name (from the key id) and local id
            //
            ASN1EncodableVector kSeq = new ASN1EncodableVector();
            Certificate ct = engineGetCertificate(name);
            kSeq.add(pkcs_9_at_localKeyId);
            kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey())));
            kName.add(new DERSequence(kSeq));
            kSeq = new ASN1EncodableVector();
            kSeq.add(pkcs_9_at_friendlyName);
            kSeq.add(new DERSet(new DERBMPString(name)));
            kName.add(new DERSequence(kSeq));
        }
        SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.getDERObject(), new DERSet(kName));
        keyS.add(kBag);
    }
    byte[] keySEncoded = new DERSequence(keyS).getDEREncoded();
    BERConstructedOctetString keyString = new BERConstructedOctetString(keySEncoded);
    //
    // certificate processing
    //
    byte[] cSalt = new byte[SALT_SIZE];
    random.nextBytes(cSalt);
    ASN1EncodableVector certSeq = new ASN1EncodableVector();
    PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS);
    AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.getDERObject());
    Hashtable doneCerts = new Hashtable();
    Enumeration cs = keys.keys();
    while (cs.hasMoreElements()) {
        try {
            String name = (String) cs.nextElement();
            Certificate cert = engineGetCertificate(name);
            boolean cAttrSet = false;
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(name)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
                }
                //
                if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                    bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey()));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_localKeyId);
                fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey())));
                fName.add(new DERSequence(fSeq));
                fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(name)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = certs.keys();
    while (cs.hasMoreElements()) {
        try {
            String certId = (String) cs.nextElement();
            Certificate cert = (Certificate) certs.get(certId);
            boolean cAttrSet = false;
            if (keys.get(certId) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(certId)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(certId)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = chainCerts.keys();
    while (cs.hasMoreElements()) {
        try {
            CertId certId = (CertId) cs.nextElement();
            Certificate cert = (Certificate) chainCerts.get(certId);
            if (doneCerts.get(cert) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                }
            }
            SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
            certSeq.add(sBag);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    byte[] certSeqEncoded = new DERSequence(certSeq).getDEREncoded();
    byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded);
    EncryptedData cInfo = new EncryptedData(data, cAlgId, new BERConstructedOctetString(certBytes));
    ContentInfo[] info = new ContentInfo[] { new ContentInfo(data, keyString), new ContentInfo(encryptedData, cInfo.getDERObject()) };
    AuthenticatedSafe auth = new AuthenticatedSafe(info);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream asn1Out;
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(bOut);
    } else {
        asn1Out = new BEROutputStream(bOut);
    }
    asn1Out.writeObject(auth);
    byte[] pkg = bOut.toByteArray();
    ContentInfo mainInfo = new ContentInfo(data, new BERConstructedOctetString(pkg));
    //
    // create the mac
    //
    byte[] mSalt = new byte[20];
    int itCount = MIN_ITERATIONS;
    random.nextBytes(mSalt);
    byte[] data = ((ASN1OctetString) mainInfo.getContent()).getOctets();
    MacData mData;
    try {
        byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data);
        // BEGIN android-changed
        AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE);
        // END android-changed
        DigestInfo dInfo = new DigestInfo(algId, res);
        mData = new MacData(dInfo, mSalt, itCount);
    } catch (Exception e) {
        throw new IOException("error constructing MAC: " + e.toString());
    }
    //
    // output the Pfx
    //
    Pfx pfx = new Pfx(mainInfo, mData);
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(stream);
    } else {
        asn1Out = new BEROutputStream(stream);
    }
    asn1Out.writeObject(pfx);
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PrivateKey(java.security.PrivateKey) AuthenticatedSafe(org.bouncycastle.asn1.pkcs.AuthenticatedSafe) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERSet(org.bouncycastle.asn1.DERSet) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) EncryptedData(org.bouncycastle.asn1.pkcs.EncryptedData) MacData(org.bouncycastle.asn1.pkcs.MacData) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) Pfx(org.bouncycastle.asn1.pkcs.Pfx) Hashtable(java.util.Hashtable) BEROutputStream(org.bouncycastle.asn1.BEROutputStream) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SafeBag(org.bouncycastle.asn1.pkcs.SafeBag) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) 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) CertBag(org.bouncycastle.asn1.pkcs.CertBag) PKCS12PBEParams(org.bouncycastle.asn1.pkcs.PKCS12PBEParams) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) DEROutputStream(org.bouncycastle.asn1.DEROutputStream)

Example 3 with CertId

use of org.bouncycastle.asn1.crmf.CertId in project poi by apache.

the class XAdESXLSignatureFacet method postSign.

@Override
public void postSign(Document document) throws MarshalException {
    LOG.log(POILogger.DEBUG, "XAdES-X-L post sign phase");
    QualifyingPropertiesDocument qualDoc = null;
    QualifyingPropertiesType qualProps = null;
    // check for XAdES-BES
    NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties");
    if (qualNl.getLength() == 1) {
        try {
            qualDoc = QualifyingPropertiesDocument.Factory.parse(qualNl.item(0), DEFAULT_XML_OPTIONS);
        } catch (XmlException e) {
            throw new MarshalException(e);
        }
        qualProps = qualDoc.getQualifyingProperties();
    } else {
        throw new MarshalException("no XAdES-BES extension present");
    }
    // create basic XML container structure
    UnsignedPropertiesType unsignedProps = qualProps.getUnsignedProperties();
    if (unsignedProps == null) {
        unsignedProps = qualProps.addNewUnsignedProperties();
    }
    UnsignedSignaturePropertiesType unsignedSigProps = unsignedProps.getUnsignedSignatureProperties();
    if (unsignedSigProps == null) {
        unsignedSigProps = unsignedProps.addNewUnsignedSignatureProperties();
    }
    // create the XAdES-T time-stamp
    NodeList nlSigVal = document.getElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue");
    if (nlSigVal.getLength() != 1) {
        throw new IllegalArgumentException("SignatureValue is not set.");
    }
    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.log(POILogger.DEBUG, "creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(nlSigVal.item(0)), tsaRevocationDataXadesT);
    // marshal the XAdES-T extension
    unsignedSigProps.addNewSignatureTimeStamp().set(signatureTimeStamp);
    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        insertXChild(unsignedSigProps, validationData);
    }
    if (signatureConfig.getRevocationDataService() == null) {
        /*
             * Without revocation data service we cannot construct the XAdES-C
             * extension.
             */
        return;
    }
    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = unsignedSigProps.addNewCompleteCertificateRefs();
    CertIDListType certIdList = completeCertificateRefs.addNewCertRefs();
    /*
         * We skip the signing certificate itself according to section
         * 4.4.3.2 of the XAdES 1.4.1 specification.
         */
    List<X509Certificate> certChain = signatureConfig.getSigningCertificateChain();
    int chainSize = certChain.size();
    if (chainSize > 1) {
        for (X509Certificate cert : certChain.subList(1, chainSize)) {
            CertIDType certId = certIdList.addNewCert();
            XAdESSignatureFacet.setCertID(certId, signatureConfig, false, cert);
        }
    }
    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = unsignedSigProps.addNewCompleteRevocationRefs();
    RevocationData revocationData = signatureConfig.getRevocationDataService().getRevocationData(certChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = completeRevocationRefs.addNewCRLRefs();
        completeRevocationRefs.setCRLRefs(crlRefs);
        for (byte[] encodedCrl : revocationData.getCRLs()) {
            CRLRefType crlRef = crlRefs.addNewCRLRef();
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }
            CRLIdentifierType crlIdentifier = crlRef.addNewCRLIdentifier();
            String issuerName = crl.getIssuerDN().getName().replace(",", ", ");
            crlIdentifier.setIssuer(issuerName);
            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
            cal.setTime(crl.getThisUpdate());
            crlIdentifier.setIssueTime(cal);
            crlIdentifier.setNumber(getCrlNumber(crl));
            DigestAlgAndValueType digestAlgAndValue = crlRef.addNewDigestAlgAndValue();
            XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, encodedCrl, signatureConfig.getDigestAlgo());
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = completeRevocationRefs.addNewOCSPRefs();
        for (byte[] ocsp : revocationData.getOCSPs()) {
            try {
                OCSPRefType ocspRef = ocspRefs.addNewOCSPRef();
                DigestAlgAndValueType digestAlgAndValue = ocspRef.addNewDigestAlgAndValue();
                XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, ocsp, signatureConfig.getDigestAlgo());
                OCSPIdentifierType ocspIdentifier = ocspRef.addNewOCSPIdentifier();
                OCSPResp ocspResp = new OCSPResp(ocsp);
                BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResp.getResponseObject();
                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
                cal.setTime(basicOcspResp.getProducedAt());
                ocspIdentifier.setProducedAt(cal);
                ResponderIDType responderId = ocspIdentifier.addNewResponderID();
                RespID respId = basicOcspResp.getResponderId();
                ResponderID ocspResponderId = respId.toASN1Primitive();
                DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Primitive();
                if (2 == derTaggedObject.getTagNo()) {
                    ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                    byte[] key = keyHashOctetString.getOctets();
                    responderId.setByKey(key);
                } else {
                    X500Name name = X500Name.getInstance(derTaggedObject.getObject());
                    String nameStr = name.toString();
                    responderId.setByName(nameStr);
                }
            } catch (Exception e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
        }
    }
    // marshal XAdES-C
    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new ArrayList<Node>();
    timeStampNodesXadesX1.add(nlSigVal.item(0));
    timeStampNodesXadesX1.add(signatureTimeStamp.getDomNode());
    timeStampNodesXadesX1.add(completeCertificateRefs.getDomNode());
    timeStampNodesXadesX1.add(completeRevocationRefs.getDomNode());
    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.log(POILogger.DEBUG, "creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1);
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        ValidationDataType timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
        insertXChild(unsignedSigProps, timeStampXadesX1ValidationData);
    }
    // marshal XAdES-X
    unsignedSigProps.addNewSigAndRefsTimeStamp().set(timeStampXadesX1);
    // XAdES-X-L
    CertificateValuesType certificateValues = unsignedSigProps.addNewCertificateValues();
    for (X509Certificate certificate : certChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = certificateValues.addNewEncapsulatedX509Certificate();
        try {
            encapsulatedPKIDataType.setByteArrayValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
    }
    RevocationValuesType revocationValues = unsignedSigProps.addNewRevocationValues();
    createRevocationValues(revocationValues, revocationData);
    // marshal XAdES-X-L
    Node n = document.importNode(qualProps.getDomNode(), true);
    qualNl.item(0).getParentNode().replaceChild(n, qualNl.item(0));
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) MarshalException(javax.xml.crypto.MarshalException) X509CRL(java.security.cert.X509CRL) ValidationDataType(org.etsi.uri.x01903.v14.ValidationDataType) Node(org.w3c.dom.Node) ResponderID(org.bouncycastle.asn1.ocsp.ResponderID) ArrayList(java.util.ArrayList) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) X500Name(org.bouncycastle.asn1.x500.X500Name) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) CRLException(java.security.cert.CRLException) RevocationData(org.apache.poi.poifs.crypt.dsig.services.RevocationData) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) NodeList(org.w3c.dom.NodeList) Calendar(java.util.Calendar) CertificateEncodingException(java.security.cert.CertificateEncodingException) X509Certificate(java.security.cert.X509Certificate) MarshalException(javax.xml.crypto.MarshalException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) XmlException(org.apache.xmlbeans.XmlException) CRLException(java.security.cert.CRLException) CertificateEncodingException(java.security.cert.CertificateEncodingException) ByteArrayInputStream(java.io.ByteArrayInputStream) XmlException(org.apache.xmlbeans.XmlException) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) RespID(org.bouncycastle.cert.ocsp.RespID)

Example 4 with CertId

use of org.bouncycastle.asn1.crmf.CertId in project poi by apache.

the class PkiTestUtils method createOcspResp.

public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
    CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
    // request
    //create a nonce to avoid replay attack
    BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
    DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
    Extensions exts = new Extensions(ext);
    OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(certId);
    ocspReqBuilder.setRequestExtensions(exts);
    OCSPReq ocspReq = ocspReqBuilder.build();
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
    basicOCSPRespBuilder.setResponseExtensions(exts);
    // request processing
    Req[] requestList = ocspReq.getRequestList();
    for (Req ocspRequest : requestList) {
        CertificateID certificateID = ocspRequest.getCertID();
        CertificateStatus certificateStatus = CertificateStatus.GOOD;
        if (revoked) {
            certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
        }
        basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
    }
    // basic response generation
    X509CertificateHolder[] chain = null;
    if (!ocspResponderCertificate.equals(issuerCertificate)) {
        // TODO: HorribleProxy can't convert array input params yet
        chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
    }
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
    BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
    OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
    OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
    return ocspResp;
}
Also used : BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Example 5 with CertId

use of org.bouncycastle.asn1.crmf.CertId in project XobotOS by xamarin.

the class CertBag method toASN1Object.

public DERObject toASN1Object() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(certId);
    v.add(new DERTaggedObject(0, certValue));
    return new DERSequence(v);
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector)

Aggregations

DEROctetString (org.bouncycastle.asn1.DEROctetString)26 X509Certificate (java.security.cert.X509Certificate)19 IOException (java.io.IOException)18 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)15 CertificateException (java.security.cert.CertificateException)12 PreparedStatement (java.sql.PreparedStatement)12 SQLException (java.sql.SQLException)12 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)11 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)11 Extension (org.bouncycastle.asn1.x509.Extension)10 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)10 BigInteger (java.math.BigInteger)9 CertificateEncodingException (java.security.cert.CertificateEncodingException)9 Date (java.util.Date)9 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)9 Certificate (java.security.cert.Certificate)8 CertID (org.bouncycastle.asn1.ocsp.CertID)8 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)8 OperationException (org.xipki.ca.api.OperationException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7