Search in sources :

Example 1 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project apollo by salesforce.

the class Certificates method sign.

public static X509Certificate sign(boolean useSubjectKeyIdentifier, BcX500NameDnImpl signerDn, KeyPair signerKeyPair, BigInteger serialNumber, Instant notBefore, Instant notAfter, List<CertExtension> extensions, BcX500NameDnImpl dn, PublicKey signedKey) {
    try {
        final ContentSigner sigGen = new JcaContentSignerBuilder(SignatureAlgorithm.lookup(signerKeyPair.getPrivate()).signatureInstanceName()).build(signerKeyPair.getPrivate());
        final SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(signedKey.getEncoded());
        final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(signerDn.getX500Name(), serialNumber, Date.from(notBefore), Date.from(notAfter), dn.getX500Name(), subPubKeyInfo).addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(signerKeyPair.getPublic()));
        if (useSubjectKeyIdentifier) {
            certBuilder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(signerKeyPair.getPublic()));
        }
        for (final CertExtension e : extensions) {
            certBuilder.addExtension(e.getOid(), e.isCritical(), e.getValue());
        }
        final X509CertificateHolder holder = certBuilder.build(sigGen);
        final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(holder);
        cert.checkValidity();
        cert.verify(signerKeyPair.getPublic());
        return cert;
    } catch (final OperatorCreationException | CertificateException | InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException | CertIOException e) {
        throw new IllegalStateException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertIOException(org.bouncycastle.cert.CertIOException) X509Certificate(java.security.cert.X509Certificate) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 2 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project gdmatrix by gdmatrix.

the class CMSUtils method createTimeStampRequest.

public static TimeStampReq createTimeStampRequest(byte[] message, String nonce, boolean requireCert, Extensions extensions, String digestAlgorithm, String timestampPolicy) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA1");
    byte[] hashedMsg = md.digest(message);
    ASN1ObjectIdentifier identifier = new ASN1ObjectIdentifier(digestAlgorithm);
    org.bouncycastle.asn1.tsp.MessageImprint imprint = new org.bouncycastle.asn1.tsp.MessageImprint(new AlgorithmIdentifier(identifier), hashedMsg);
    TimeStampReq request = new TimeStampReq(imprint, timestampPolicy != null ? new ASN1ObjectIdentifier(timestampPolicy) : null, nonce != null ? new ASN1Integer(nonce.getBytes()) : null, ASN1Boolean.getInstance(requireCert), extensions);
    return request;
}
Also used : TimeStampReq(org.bouncycastle.asn1.tsp.TimeStampReq) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) MessageDigest(java.security.MessageDigest) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 3 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project ca3sCore by kuehne-trustable-de.

the class CaCmpConnector method buildCertRequest.

/**
 * @param certReqId
 * @param csr
 * @param hmacSecret
 * @return PKIMessage
 * @throws GeneralSecurityException
 */
public PKIMessage buildCertRequest(long certReqId, final CSR csr, final String hmacSecret) throws GeneralSecurityException {
    // read the pem csr and verify the signature
    PKCS10CertificationRequest p10Req;
    try {
        p10Req = cryptoUtil.parseCertificateRequest(csr.getCsrBase64()).getP10Req();
    } catch (IOException e) {
        LOGGER.error("parsing csr", e);
        throw new GeneralSecurityException(e.getMessage());
    }
    List<RDN> rdnList = new ArrayList<>();
    for (de.trustable.ca3s.core.domain.RDN rdnDao : csr.getRdns()) {
        LOGGER.debug("rdnDao : " + rdnDao.getRdnAttributes());
        List<AttributeTypeAndValue> attrTVList = new ArrayList<AttributeTypeAndValue>();
        if (rdnDao != null && rdnDao.getRdnAttributes() != null) {
            for (RDNAttribute rdnAttr : rdnDao.getRdnAttributes()) {
                ASN1ObjectIdentifier aoi = new ASN1ObjectIdentifier(rdnAttr.getAttributeType());
                ASN1Encodable ae = new DERUTF8String(rdnAttr.getAttributeValue());
                AttributeTypeAndValue attrTV = new AttributeTypeAndValue(aoi, ae);
                attrTVList.add(attrTV);
            }
        }
        RDN rdn = new RDN(attrTVList.toArray(new AttributeTypeAndValue[attrTVList.size()]));
        LOGGER.debug("rdn : " + rdn.size() + " elements");
        rdnList.add(rdn);
    }
    X500Name subjectDN = new X500Name(rdnList.toArray(new RDN[rdnList.size()]));
    LOGGER.debug("subjectDN : " + subjectDN);
    Collection<Extension> certExtList = new ArrayList<>();
    // copy CSR attributes to Extension list
    for (Attribute attribute : p10Req.getAttributes()) {
        for (ASN1Encodable asn1Encodable : attribute.getAttributeValues()) {
            if (asn1Encodable != null) {
                try {
                    Extensions extensions = Extensions.getInstance(asn1Encodable);
                    for (ASN1ObjectIdentifier oid : extensions.getExtensionOIDs()) {
                        LOGGER.debug("copying oid '" + oid.toString() + "' from csr to PKIMessage");
                        certExtList.add(extensions.getExtension(oid));
                    }
                } catch (IllegalArgumentException iae) {
                    LOGGER.debug("processing asn1 value  '" + asn1Encodable + "' caused exception", iae);
                }
            }
        }
    }
    final SubjectPublicKeyInfo keyInfo = p10Req.getSubjectPublicKeyInfo();
    return cryptoUtil.buildCertRequest(certReqId, subjectDN, certExtList, keyInfo, hmacSecret);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) RDNAttribute(de.trustable.ca3s.core.domain.RDNAttribute) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) RDNAttribute(de.trustable.ca3s.core.domain.RDNAttribute) CsrAttribute(de.trustable.ca3s.core.domain.CsrAttribute) Attribute(org.bouncycastle.asn1.pkcs.Attribute) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue) Extension(org.bouncycastle.asn1.x509.Extension) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) RDN(org.bouncycastle.asn1.x500.RDN) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 4 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project ca3sCore by kuehne-trustable-de.

the class CaInternalConnector method signCertificateRequest.

public Certificate signCertificateRequest(CSR csr, CAConnectorConfig caConfig) throws GeneralSecurityException {
    try {
        csrUtil.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_CA_PROCESSING_STARTED_TIMESTAMP, "" + System.currentTimeMillis(), false);
        csr.setStatus(CsrStatus.PROCESSING);
        Certificate intermediate = getIntermediate();
        PrivateKey privKeyIntermediate = certUtil.getPrivateKey(intermediate);
        KeyPair kpIntermediate = new KeyPair(certUtil.convertPemToCertificate(intermediate.getContent()).getPublicKey(), privKeyIntermediate);
        PKCS10CertificationRequest p10 = cryptoUtil.convertPemToPKCS10CertificationRequest(csr.getCsrBase64());
        GeneralNames gns = null;
        org.bouncycastle.asn1.pkcs.Attribute[] certAttributes = p10.getAttributes();
        for (org.bouncycastle.asn1.pkcs.Attribute attribute : certAttributes) {
            if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            }
        }
        X509Certificate x509Cert = cryptoUtil.issueCertificate(new X500Name(intermediate.getSubject()), kpIntermediate, p10.getSubject(), p10.getSubjectPublicKeyInfo(), Calendar.YEAR, 1, gns, null, PKILevel.END_ENTITY);
        Certificate cert = certUtil.createCertificate(x509Cert.getEncoded(), csr, "", false);
        cert.setRevocationCA(caConfig);
        certRepository.save(cert);
        csrUtil.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_CA_PROCESSING_FINISHED_TIMESTAMP, "" + System.currentTimeMillis(), true);
        csr.setStatus(CsrStatus.ISSUED);
        csrRepository.save(csr);
        return cert;
    } catch (IOException e) {
        LOG.info("Problem signing certificate request", e);
        throw new GeneralSecurityException(e);
    }
/*
		RDN[] rdnArr = new RDN[csr.getRdns().size()];

		int i = 0;
		for(de.trustable.ca3s.core.domain.RDN rdn:csr.getRdns()) {
			LOG.debug("RDN contains #{}", rdn.getRdnAttributes().size());
			int attLen = rdn.getRdnAttributes().size();
			AttributeTypeAndValue[] atavArr = new AttributeTypeAndValue[attLen];
			int j = 0;
			for(RDNAttribute rdnAtt: rdn.getRdnAttributes()) {
				AttributeTypeAndValue atav = new AttributeTypeAndValue( rdnAtt.getAttributeType(), new DEROctetString(rdnAtt.getAttributeValue().getBytes()));
			}
			rdnArr[i++] = new RDN(atav);
		}
		X500Name subject = new X500Name(csr.getRdns());
*/
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) CertificateAttribute(de.trustable.ca3s.core.domain.CertificateAttribute) CsrAttribute(de.trustable.ca3s.core.domain.CsrAttribute) GeneralSecurityException(java.security.GeneralSecurityException) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509Certificate(java.security.cert.X509Certificate) Certificate(de.trustable.ca3s.core.domain.Certificate)

Example 5 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project modules by assimbly.

the class CertificatesUtil method selfsignCertificate2.

public static Certificate selfsignCertificate2(KeyPair keyPair, String subjectDN) throws OperatorCreationException, CertificateException, IOException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    long now = System.currentTimeMillis();
    Date startDate = new Date(now);
    X500Name dnName = new X500Name("CN=" + subjectDN);
    // <-- Using the current timestamp as the certificate serial number
    BigInteger certSerialNumber = new BigInteger(Long.toString(now));
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    // <-- 2 Yr validity
    calendar.add(Calendar.YEAR, 2);
    Date endDate = calendar.getTime();
    // <-- Use appropriate signature algorithm based on your keyPair algorithm.
    String signatureAlgorithm = "SHA256WithRSA";
    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic());
    // Extensions --------------------------
    // Basic Constraints
    // <-- true for CA, false for EndEntity
    BasicConstraints basicConstraints = new BasicConstraints(true);
    // Basic Constraints is usually marked as critical.
    certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);
    return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) Calendar(java.util.Calendar) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) Provider(java.security.Provider) BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

Extensions (org.bouncycastle.asn1.x509.Extensions)113 Extension (org.bouncycastle.asn1.x509.Extension)89 IOException (java.io.IOException)72 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)67 Enumeration (java.util.Enumeration)57 HashSet (java.util.HashSet)49 DEROctetString (org.bouncycastle.asn1.DEROctetString)49 X500Name (org.bouncycastle.asn1.x500.X500Name)46 BigInteger (java.math.BigInteger)45 Set (java.util.Set)36 X509Certificate (java.security.cert.X509Certificate)35 Date (java.util.Date)35 GeneralName (org.bouncycastle.asn1.x509.GeneralName)35 ContentSigner (org.bouncycastle.operator.ContentSigner)32 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)29 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)28 ArrayList (java.util.ArrayList)28 CertificateException (java.security.cert.CertificateException)27 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)27