Search in sources :

Example 61 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project platformlayer by platformlayer.

the class SimpleCertificateAuthority method selfSign.

public static X509Certificate selfSign(String csr, KeyPair keyPair) throws OpsException {
    try {
        PKCS10CertificationRequest csrHolder = parseCsr(csr);
        SubjectPublicKeyInfo subjectPublicKeyInfo = csrHolder.getSubjectPublicKeyInfo();
        X500Name subject = csrHolder.getSubject();
        // Self sign
        X500Name issuer = subject;
        PrivateKey issuerPrivateKey = keyPair.getPrivate();
        Certificate certificate = signCertificate(issuer, issuerPrivateKey, subject, subjectPublicKeyInfo);
        return toX509(certificate);
    } catch (IOException e) {
        throw new OpsException("Error reading CSR", e);
    }
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) OpsException(org.platformlayer.ops.OpsException) PrivateKey(java.security.PrivateKey) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 62 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project platformlayer by platformlayer.

the class SimpleCertificateAuthority method selfSign.

public static X509Certificate selfSign(X500Principal subject, KeyPair keyPair) throws OpsException {
    X500Principal issuer = subject;
    Certificate certificate = signCertificate(BouncyCastleHelpers.toX500Name(issuer), keyPair.getPrivate(), BouncyCastleHelpers.toX500Name(subject), BouncyCastleHelpers.toSubjectPublicKeyInfo(keyPair.getPublic()));
    return toX509(certificate);
}
Also used : X500Principal(javax.security.auth.x500.X500Principal) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 63 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project xipki by xipki.

the class AbstractOcspRequestor method buildRequest.

// method ask
private OCSPRequest buildRequest(X509Certificate caCert, BigInteger[] serialNumbers, byte[] nonce, RequestOptions requestOptions) throws OcspRequestorException {
    HashAlgo hashAlgo = HashAlgo.getInstance(requestOptions.getHashAlgorithmId());
    if (hashAlgo == null) {
        throw new OcspRequestorException("unknown HashAlgo " + requestOptions.getHashAlgorithmId().getId());
    }
    List<AlgorithmIdentifier> 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 (AlgorithmIdentifier algId : prefSigAlgs) {
            vec.add(new DERSequence(algId));
        }
        ASN1Sequence extnValue = new DERSequence(vec);
        Extension extn;
        try {
            extn = new Extension(ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
        } catch (IOException ex) {
            throw new OcspRequestorException(ex.getMessage(), ex);
        }
        extensions.add(extn);
    }
    if (CollectionUtil.isNonEmpty(extensions)) {
        reqBuilder.setRequestExtensions(new Extensions(extensions.toArray(new Extension[0])));
    }
    try {
        DEROctetString issuerNameHash = new DEROctetString(hashAlgo.hash(caCert.getSubjectX500Principal().getEncoded()));
        TBSCertificate tbsCert;
        try {
            tbsCert = TBSCertificate.getInstance(caCert.getTBSCertificate());
        } catch (CertificateEncodingException ex) {
            throw new OcspRequestorException(ex);
        }
        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");
                    }
                    X509Certificate cert = null;
                    if (StringUtil.isNotBlank(signerCertFile)) {
                        try {
                            cert = X509Util.parseCert(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.getBcCertificate().getSubject());
            X509CertificateHolder[] certChain0 = signer.getBcCertificateChain();
            Certificate[] certChain = new Certificate[certChain0.length];
            for (int i = 0; i < certChain.length; i++) {
                certChain[i] = certChain0[i].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 : HashAlgo(org.xipki.security.HashAlgo) CertID(org.bouncycastle.asn1.ocsp.CertID) CertificateException(java.security.cert.CertificateException) Extensions(org.bouncycastle.asn1.x509.Extensions) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) SignerConf(org.xipki.security.SignerConf) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ConcurrentBagEntrySigner(org.xipki.security.ConcurrentBagEntrySigner) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) OcspNonceUnmatchedException(org.xipki.ocsp.client.api.OcspNonceUnmatchedException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) OcspResponseException(org.xipki.ocsp.client.api.OcspResponseException) OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ResponderUnreachableException(org.xipki.ocsp.client.api.ResponderUnreachableException) OcspTargetUnmatchedException(org.xipki.ocsp.client.api.OcspTargetUnmatchedException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) InvalidOcspResponseException(org.xipki.ocsp.client.api.InvalidOcspResponseException) Extension(org.bouncycastle.asn1.x509.Extension) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 64 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project xipki by xipki.

the class OcspCertStoreFromCaDbImporter method importIssuer0.

private void importIssuer0(CaType issuer, String sql, PreparedStatement ps, List<CaType> cas, List<Integer> relatedCaIds) throws IOException, DataAccessException, CertificateException {
    try {
        byte[] encodedCert = binary(issuer.getCert());
        // retrieve the revocation information of the CA, if possible
        CaType ca = null;
        for (CaType caType : cas) {
            if (Arrays.equals(encodedCert, binary(caType.getCert()))) {
                ca = caType;
                break;
            }
        }
        if (ca == null) {
            return;
        }
        relatedCaIds.add(issuer.getId());
        Certificate cert;
        try {
            cert = Certificate.getInstance(encodedCert);
        } catch (RuntimeException ex) {
            String msg = "could not parse certificate of issuer " + issuer.getId();
            LogUtil.error(LOG, ex, msg);
            throw new CertificateException(ex.getMessage(), ex);
        }
        int idx = 1;
        ps.setInt(idx++, issuer.getId());
        ps.setString(idx++, X509Util.cutX500Name(cert.getSubject(), maxX500nameLen));
        ps.setLong(idx++, cert.getTBSCertificate().getStartDate().getDate().getTime() / 1000);
        ps.setLong(idx++, cert.getTBSCertificate().getEndDate().getDate().getTime() / 1000);
        ps.setString(idx++, HashAlgo.SHA1.base64Hash(encodedCert));
        setBoolean(ps, idx++, ca.isRevoked());
        setInt(ps, idx++, ca.getRevReason());
        setLong(ps, idx++, ca.getRevTime());
        setLong(ps, idx++, ca.getRevInvTime());
        ps.setString(idx++, Base64.encodeToString(encodedCert));
        ps.execute();
    } catch (SQLException ex) {
        System.err.println("could not import issuer with id=" + issuer.getId());
        throw translate(sql, ex);
    } catch (CertificateException ex) {
        System.err.println("could not import issuer with id=" + issuer.getId());
        throw ex;
    }
}
Also used : SQLException(java.sql.SQLException) CertificateException(java.security.cert.CertificateException) CaType(org.xipki.ca.dbtool.jaxb.ca.CaType) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 65 with Certificate

use of com.beanit.asn1bean.compiler.pkix1explicit88.Certificate in project xipki by xipki.

the class X509Ca method addXipkiCertset.

// method generateCrl
/**
 * Add XiPKI extension CrlCertSet.
 *
 * <pre>
 * Xipki-CrlCertSet ::= SET OF Xipki-CrlCert
 *
 * Xipki-CrlCert ::= SEQUENCE {
 *         serial            INTEGER
 *         cert        [0] EXPLICIT    Certificate OPTIONAL
 *         profileName [1] EXPLICIT    UTF8String    OPTIONAL
 *         }
 * </pre>
 */
private void addXipkiCertset(X509v2CRLBuilder crlBuilder, boolean deltaCrl, CrlControl control, Date notExpireAt, boolean onlyCaCerts, boolean onlyUserCerts) throws OperationException {
    if (deltaCrl || !control.isXipkiCertsetIncluded()) {
        return;
    }
    ASN1EncodableVector vector = new ASN1EncodableVector();
    final int numEntries = 100;
    long startId = 1;
    List<SerialWithId> serials;
    do {
        serials = certstore.getCertSerials(caIdent, notExpireAt, startId, numEntries, false, onlyCaCerts, onlyUserCerts);
        long maxId = 1;
        for (SerialWithId sid : serials) {
            if (sid.getId() > maxId) {
                maxId = sid.getId();
            }
            ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(new ASN1Integer(sid.getSerial()));
            Integer profileId = null;
            if (control.isXipkiCertsetCertIncluded()) {
                X509CertificateInfo certInfo;
                try {
                    certInfo = certstore.getCertificateInfoForId(caIdent, caCert, sid.getId(), caIdNameMap);
                } catch (CertificateException ex) {
                    throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CertificateException: " + ex.getMessage());
                }
                Certificate cert = Certificate.getInstance(certInfo.getCert().getEncodedCert());
                vec.add(new DERTaggedObject(true, 0, cert));
                if (control.isXipkiCertsetProfilenameIncluded()) {
                    profileId = certInfo.getProfile().getId();
                }
            } else if (control.isXipkiCertsetProfilenameIncluded()) {
                profileId = certstore.getCertProfileForId(caIdent, sid.getId());
            }
            if (profileId != null) {
                String profileName = caIdNameMap.getCertprofileName(profileId);
                vec.add(new DERTaggedObject(true, 1, new DERUTF8String(profileName)));
            }
            vector.add(new DERSequence(vec));
        }
        // end for
        startId = maxId + 1;
    } while (serials.size() >= numEntries);
    try {
        crlBuilder.addExtension(ObjectIdentifiers.id_xipki_ext_crlCertset, false, new DERSet(vector));
    } catch (CertIOException ex) {
        throw new OperationException(ErrorCode.INVALID_EXTENSION, "CertIOException: " + ex.getMessage());
    }
}
Also used : DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) X509CertificateInfo(org.xipki.ca.api.publisher.x509.X509CertificateInfo) CertificateException(java.security.cert.CertificateException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERSet(org.bouncycastle.asn1.DERSet) CertIOException(org.bouncycastle.cert.CertIOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) BigInteger(java.math.BigInteger) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) OperationException(org.xipki.ca.api.OperationException) Certificate(org.bouncycastle.asn1.x509.Certificate) X509Certificate(java.security.cert.X509Certificate)

Aggregations

Certificate (org.bouncycastle.asn1.x509.Certificate)53 IOException (java.io.IOException)40 X509Certificate (java.security.cert.X509Certificate)37 CertificateException (java.security.cert.CertificateException)27 File (java.io.File)11 Test (org.junit.Test)10 BigInteger (java.math.BigInteger)9 CertificateEncodingException (java.security.cert.CertificateEncodingException)9 TBSCertificate (org.bouncycastle.asn1.x509.TBSCertificate)9 Test (org.junit.jupiter.api.Test)9 Certificate (com.google.cloud.security.privateca.v1.Certificate)8 CertificateAuthorityServiceClient (com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient)8 SQLException (java.sql.SQLException)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)7 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)7 Certificate (com.beanit.asn1bean.compiler.pkix1explicit88.Certificate)6 Extension (org.bouncycastle.asn1.x509.Extension)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6 Date (java.util.Date)5