Search in sources :

Example 31 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project xipki by xipki.

the class AbstractOcspRequestor method buildRequest.

// method ask
private OCSPRequest buildRequest(X509Cert caCert, BigInteger[] serialNumbers, byte[] nonce, RequestOptions requestOptions) throws OcspRequestorException {
    HashAlgo hashAlgo = requestOptions.getHashAlgorithm();
    List<SignAlgo> prefSigAlgs = requestOptions.getPreferredSignatureAlgorithms();
    XiOCSPReqBuilder reqBuilder = new XiOCSPReqBuilder();
    List<Extension> extensions = new LinkedList<>();
    if (nonce != null) {
        extensions.add(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)));
    }
    if (prefSigAlgs != null && prefSigAlgs.size() > 0) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (SignAlgo algId : prefSigAlgs) {
            vec.add(new DERSequence(algId.getAlgorithmIdentifier()));
        }
        ASN1Sequence extnValue = new DERSequence(vec);
        Extension extn;
        try {
            extn = new Extension(ObjectIdentifiers.Extn.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
        } catch (IOException ex) {
            throw new OcspRequestorException(ex.getMessage(), ex);
        }
        extensions.add(extn);
    }
    if (CollectionUtil.isNotEmpty(extensions)) {
        reqBuilder.setRequestExtensions(new Extensions(extensions.toArray(new Extension[0])));
    }
    try {
        DEROctetString issuerNameHash = new DEROctetString(hashAlgo.hash(caCert.getSubject().getEncoded()));
        TBSCertificate tbsCert = caCert.toBcCert().toASN1Structure().getTBSCertificate();
        DEROctetString issuerKeyHash = new DEROctetString(hashAlgo.hash(tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getOctets()));
        for (BigInteger serialNumber : serialNumbers) {
            CertID certId = new CertID(hashAlgo.getAlgorithmIdentifier(), issuerNameHash, issuerKeyHash, new ASN1Integer(serialNumber));
            reqBuilder.addRequest(certId);
        }
        if (requestOptions.isSignRequest()) {
            synchronized (signerLock) {
                if (signer == null) {
                    if (StringUtil.isBlank(signerType)) {
                        throw new OcspRequestorException("signerType is not configured");
                    }
                    if (StringUtil.isBlank(signerConf)) {
                        throw new OcspRequestorException("signerConf is not configured");
                    }
                    X509Cert cert = null;
                    if (StringUtil.isNotBlank(signerCertFile)) {
                        try {
                            cert = X509Util.parseCert(new File(signerCertFile));
                        } catch (CertificateException ex) {
                            throw new OcspRequestorException("could not parse certificate " + signerCertFile + ": " + ex.getMessage());
                        }
                    }
                    try {
                        signer = getSecurityFactory().createSigner(signerType, new SignerConf(signerConf), cert);
                    } catch (Exception ex) {
                        throw new OcspRequestorException("could not create signer: " + ex.getMessage());
                    }
                }
            // end if
            }
            // end synchronized
            reqBuilder.setRequestorName(signer.getCertificate().getSubject());
            X509Cert[] certChain0 = signer.getCertificateChain();
            Certificate[] certChain = new Certificate[certChain0.length];
            for (int i = 0; i < certChain.length; i++) {
                certChain[i] = certChain0[i].toBcCert().toASN1Structure();
            }
            ConcurrentBagEntrySigner signer0;
            try {
                signer0 = signer.borrowSigner();
            } catch (NoIdleSignerException ex) {
                throw new OcspRequestorException("NoIdleSignerException: " + ex.getMessage());
            }
            try {
                return reqBuilder.build(signer0.value(), certChain);
            } finally {
                signer.requiteSigner(signer0);
            }
        } else {
            return reqBuilder.build();
        }
    // end if
    } catch (OCSPException | IOException ex) {
        throw new OcspRequestorException(ex.getMessage(), ex);
    }
}
Also used : CertID(org.bouncycastle.asn1.ocsp.CertID) CertificateException(java.security.cert.CertificateException) Extensions(org.bouncycastle.asn1.x509.Extensions) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) IOException(java.io.IOException) LinkedList(java.util.LinkedList) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) CertificateEncodingException(java.security.cert.CertificateEncodingException) Extension(org.bouncycastle.asn1.x509.Extension) BigInteger(java.math.BigInteger) File(java.io.File) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 32 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project xipki by xipki.

the class X509Cert method checkBcSignature.

private void checkBcSignature(PublicKey key, Signature signature) throws CertificateException, SignatureException, InvalidKeyException {
    Certificate c = bcInstance.toASN1Structure();
    if (!c.getSignatureAlgorithm().equals(c.getTBSCertificate().getSignature())) {
        throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
    }
    signature.initVerify(key);
    try {
        signature.update(c.getTBSCertificate().getEncoded());
    } catch (IOException ex) {
        throw new CertificateException("error encoding TBSCertificate");
    }
    if (!signature.verify(c.getSignature().getBytes())) {
        throw new SignatureException("certificate does not verify with supplied key");
    }
}
Also used : CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 33 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project xipki by xipki.

the class ImportCrl method addCertificate.

// method getCertInfo
private void addCertificate(AtomicLong maxId, int crlInfoId, CertWrapper caCert, X509Cert cert, String certLogId) throws DataAccessException {
    int caId = caCert.databaseId;
    // not issued by the given issuer
    if (!caCert.subject.equals(cert.getIssuer())) {
        LOG.warn("certificate {} is not issued by the given CA, ignore it", certLogId);
        return;
    }
    // we don't use the binary read from file, since it may contains redundant ending bytes.
    byte[] encodedCert = cert.getEncoded();
    String b64CertHash = certhashAlgo.base64Hash(encodedCert);
    if (caCert.subjectKeyIdentifier != null) {
        byte[] aki = cert.getAuthorityKeyId();
        if (aki == null || !Arrays.equals(caCert.subjectKeyIdentifier, aki)) {
            LOG.warn("certificate {} is not issued by the given CA, ignore it", certLogId);
            return;
        }
    }
    // end if
    LOG.info("Importing certificate {}", certLogId);
    CertInfo existingCertInfo = getCertInfo(caId, cert.getSerialNumber());
    PreparedStatement ps;
    String sql = null;
    try {
        if (existingCertInfo == null) {
            sql = SQL_INSERT_CERT;
            ps = psInsertCert;
            long id = maxId.incrementAndGet();
            int offset = 1;
            ps.setLong(offset++, id);
            // ISSUER ID IID
            ps.setInt(offset++, caId);
            // serial number SN
            ps.setString(offset++, cert.getSerialNumber().toString(16));
            // whether revoked REV
            ps.setInt(offset++, 0);
            // revocation reason RR
            ps.setNull(offset++, Types.SMALLINT);
            // revocation time RT
            ps.setNull(offset++, Types.BIGINT);
            ps.setNull(offset++, Types.BIGINT);
            // last update LUPDATE
            ps.setLong(offset++, System.currentTimeMillis() / 1000);
            TBSCertificate tbsCert = cert.toBcCert().toASN1Structure().getTBSCertificate();
            // not before NBEFORE
            ps.setLong(offset++, tbsCert.getStartDate().getDate().getTime() / 1000);
            // not after NAFTER
            ps.setLong(offset++, tbsCert.getEndDate().getDate().getTime() / 1000);
            ps.setInt(offset++, crlInfoId);
            ps.setString(offset, b64CertHash);
        } else {
            if (existingCertInfo.revoked || existingCertInfo.crlId != crlInfoId) {
                sql = SQL_UPDATE_CERT;
                ps = psUpdateCert;
                int offset = 1;
                // last update LUPDATE
                ps.setLong(offset++, System.currentTimeMillis() / 1000);
                TBSCertificate tbsCert = cert.toBcCert().toASN1Structure().getTBSCertificate();
                // not before NBEFORE
                ps.setLong(offset++, tbsCert.getStartDate().getDate().getTime() / 1000);
                // not after NAFTER
                ps.setLong(offset++, tbsCert.getEndDate().getDate().getTime() / 1000);
                ps.setInt(offset++, crlInfoId);
                ps.setString(offset++, b64CertHash);
                ps.setLong(offset, existingCertInfo.id);
            } else {
                sql = SQL_UPDATE_CERT_LUPDATE;
                ps = psUpdateCertLastupdate;
                // last update LUPDATE
                ps.setLong(1, System.currentTimeMillis() / 1000);
                ps.setLong(2, existingCertInfo.id);
            }
        }
        ps.executeUpdate();
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    }
    LOG.info("Imported  certificate {}", certLogId);
}
Also used : TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 34 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project OpenPDF by LibrePDF.

the class PdfPublicKeySecurityHandler method computeRecipientInfo.

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws GeneralSecurityException, IOException {
    ASN1InputStream asn1inputstream = new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificate tbsCertificate = TBSCertificate.getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbsCertificate.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbsCertificate.getIssuer(), tbsCertificate.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());
    cipher.init(1, x509certificate);
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyTransRecipientInfo(org.bouncycastle.asn1.cms.KeyTransRecipientInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) Cipher(javax.crypto.Cipher) RecipientIdentifier(org.bouncycastle.asn1.cms.RecipientIdentifier) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 35 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project syncope by apache.

the class SAML2SPEntityTest method createSelfSignedCert.

private static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    X500Name dn = new X500Name("cn=Unknown");
    V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));
    Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));
    AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
    Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));
    TBSCertificate tbsCert = certGen.generateTBSCertificate();
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));
    Certificate cert = CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
Also used : Time(org.bouncycastle.asn1.x509.Time) DERBitString(org.bouncycastle.asn1.DERBitString) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) Date(java.util.Date) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) Certificate(java.security.cert.Certificate)

Aggregations

IOException (java.io.IOException)22 TBSCertificate (org.bouncycastle.asn1.x509.TBSCertificate)22 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 CertificateException (java.security.cert.CertificateException)7 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)6 DERSequence (com.github.zhenwei.core.asn1.DERSequence)6 ByteArrayInputStream (java.io.ByteArrayInputStream)6 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 X509Certificate (java.security.cert.X509Certificate)6 DEROctetString (org.bouncycastle.asn1.DEROctetString)6 ASN1EncodableVector (com.android.org.bouncycastle.asn1.ASN1EncodableVector)5 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)5 ASN1Integer (com.android.org.bouncycastle.asn1.ASN1Integer)5 ASN1ObjectIdentifier (com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)5 DERBitString (com.android.org.bouncycastle.asn1.DERBitString)5 DERInteger (com.android.org.bouncycastle.asn1.DERInteger)5 DERSequence (com.android.org.bouncycastle.asn1.DERSequence)5 AlgorithmIdentifier (com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier)5 TBSCertificate (com.android.org.bouncycastle.asn1.x509.TBSCertificate)5 Time (com.android.org.bouncycastle.asn1.x509.Time)5