Search in sources :

Example 31 with X500Name

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

the class CMPTestEndpoint method initializeKey.

void initializeKey() throws NoSuchAlgorithmException, CertificateException, IOException {
    keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    issuer = new X500Name("CN=test root " + System.currentTimeMillis() + ", O=trustable solutions, C=DE");
    issuingCertificate = cryptoUtil.issueCertificate(issuer, keyPair, issuer, keyPair.getPublic().getEncoded(), Calendar.MONTH, 1, PKILevel.ROOT);
}
Also used : X500Name(org.bouncycastle.asn1.x500.X500Name)

Example 32 with X500Name

use of com.github.zhenwei.core.asn1.x500.X500Name 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 33 with X500Name

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

the class CaCmpConnector method revokeCertificate.

/**
 * @param certDao
 * @param crlReason
 * @param revocationDate
 * @param caConnConfig
 * @throws GeneralSecurityException
 */
public void revokeCertificate(Certificate certDao, final CRLReason crlReason, final Date revocationDate, CAConnectorConfig caConnConfig) throws GeneralSecurityException {
    String plainSecret = protUtil.unprotectString(caConnConfig.getSecret().getContentBase64());
    revokeCertificate(new X500Name(certDao.getIssuer()), new X500Name(certDao.getSubject()), new BigInteger(certDao.getSerial()), crlReason, plainSecret, caConnConfig.getCaUrl(), caConnConfig.getSelector());
}
Also used : BigInteger(java.math.BigInteger) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) X500Name(org.bouncycastle.asn1.x500.X500Name)

Example 34 with X500Name

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

the class Ca3sFallbackBundleFactory method newKeyBundle.

@Override
public KeyCertBundle newKeyBundle(final String bundleName, long minValiditySeconds) throws GeneralSecurityException {
    KeyPair localKeyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    try {
        InetAddress ip = InetAddress.getLocalHost();
        String hostname = ip.getHostName();
        LOG.debug("requesting certificate for host : " + hostname);
        String x500Name = "CN=" + hostname;
        if (!dnSuffix.trim().isEmpty()) {
            x500Name += ", " + dnSuffix;
        }
        X500Name subject = new X500Name(x500Name);
        GeneralName[] sanArray = new GeneralName[1];
        sanArray[0] = new GeneralName(GeneralName.dNSName, hostname);
        GeneralNames gns = new GeneralNames(sanArray);
        List<Map<String, Object>> extensions = new ArrayList<>();
        Map<String, Object> serverAuthMap = new HashMap<>();
        serverAuthMap.put("oid", Extension.extendedKeyUsage.getId());
        serverAuthMap.put("critical", Boolean.FALSE);
        List<String> valList = new ArrayList<>();
        valList.add(KeyPurposeId.id_kp_serverAuth.getId());
        serverAuthMap.put("value", valList);
        extensions.add(serverAuthMap);
        LOG.debug("building certificate for SAN '{}' and EKU {}", hostname, Extension.extendedKeyUsage.getId());
        X509Certificate issuedCertificate = cryptoUtil.issueCertificate(x500Issuer, getRootKeyPair(), subject, SubjectPublicKeyInfo.getInstance(localKeyPair.getPublic().getEncoded()), Calendar.HOUR, 1, gns, extensions, PKILevel.END_ENTITY);
        // build the (short) chain
        X509Certificate[] certificateChain = { issuedCertificate, getRootCertificate() };
        LOG.debug("returning temp. certificate : " + issuedCertificate);
        return new KeyCertBundle(bundleName, certificateChain, issuedCertificate, localKeyPair.getPrivate());
    } catch (IOException e) {
        // certificate creation failed with an exception not inheriting from 'GeneralSecurityException'
        throw new GeneralSecurityException(e);
    }
}
Also used : KeyPair(java.security.KeyPair) KeyCertBundle(de.trustable.ca3s.cert.bundle.KeyCertBundle) GeneralSecurityException(java.security.GeneralSecurityException) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) InetAddress(java.net.InetAddress)

Example 35 with X500Name

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

the class CertificateUtil method createCertificate.

/**
 * @param pemCert
 * @param csr
 * @param executionId
 * @param x509Cert
 * @param tbsDigestBase64
 * @return
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateParsingException
 * @throws CertificateException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws SignatureException
 */
private Certificate createCertificate(final String pemCert, final CSR csr, final String executionId, X509Certificate x509Cert, String tbsDigestBase64) throws CertificateEncodingException, IOException, NoSuchAlgorithmException, CertificateParsingException, CertificateException, InvalidKeyException, NoSuchProviderException, SignatureException {
    Certificate cert;
    LOG.debug("creating new certificate '" + x509Cert.getSubjectX500Principal().getName() + "'");
    byte[] certBytes = x509Cert.getEncoded();
    X509CertificateHolder x509CertHolder = new X509CertificateHolder(certBytes);
    cert = new Certificate();
    cert.setCertificateAttributes(new HashSet<>());
    String type = "X509V" + x509Cert.getVersion();
    cert.setType(type);
    String serial = x509Cert.getSerialNumber().toString();
    cert.setSerial(serial);
    cert.setContent(pemCert);
    if (csr != null) {
        // do not overwrite an existing CSR
        cert.setCsr(csr);
    }
    // indexed key for searching
    cert.setTbsDigest(tbsDigestBase64);
    // derive a readable description
    String desc = cryptoUtil.getDescription(x509Cert);
    cert.setDescription(CryptoService.limitLength(desc, 250));
    // good old SHA1 fingerprint
    String fingerprint = Base64.encodeBase64String(generateSHA1Fingerprint(certBytes));
    cert.setFingerprint(fingerprint);
    cert.setValidFrom(DateUtil.asInstant(x509Cert.getNotBefore()));
    cert.setValidTo(DateUtil.asInstant(x509Cert.getNotAfter()));
    cert.setActive(true);
    Date now = new Date();
    if (x509Cert.getNotBefore().after(now)) {
        cert.setActive(false);
    }
    if (x509Cert.getNotAfter().before(now)) {
        cert.setActive(false);
    }
    // initialize revocation details
    cert.setRevokedSince(null);
    cert.setRevocationReason(null);
    cert.setRevoked(false);
    if (executionId != null) {
        cert.setCreationExecutionId(executionId);
    }
    cert.setContentAddedAt(Instant.now());
    String issuer = CryptoService.limitLength(x509Cert.getIssuerX500Principal().getName(), 250);
    cert.setIssuer(issuer);
    String subject = CryptoService.limitLength(x509Cert.getSubjectX500Principal().getName(), 250);
    cert.setSubject(subject);
    cert.setSelfsigned(false);
    certificateRepository.save(cert);
    interpretBasicConstraint(x509Cert, cert);
    // add the basic key usages a attributes
    usageAsCertAttributes(x509Cert.getKeyUsage(), cert);
    // add the extended key usages a attributes
    List<String> extKeyUsageList = x509Cert.getExtendedKeyUsage();
    if (extKeyUsageList != null) {
        for (String extUsage : extKeyUsageList) {
            setCertMultiValueAttribute(cert, CertificateAttribute.ATTRIBUTE_EXTENDED_USAGE_OID, extUsage);
            setCertMultiValueAttribute(cert, CertificateAttribute.ATTRIBUTE_EXTENDED_USAGE, OidNameMapper.lookupOid(extUsage));
        }
    }
    setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ISSUER, issuer.toLowerCase());
    X500Name x500NameIssuer = x509CertHolder.getIssuer();
    insertNameAttributes(cert, CertificateAttribute.ATTRIBUTE_ISSUER, x500NameIssuer);
    setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SUBJECT, subject.toLowerCase());
    X500Name x500NameSubject = x509CertHolder.getSubject();
    insertNameAttributes(cert, CertificateAttribute.ATTRIBUTE_SUBJECT, x500NameSubject);
    setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_TYPE, type);
    JcaX509ExtensionUtils util = new JcaX509ExtensionUtils();
    // build two SKI variants for cert identification
    SubjectKeyIdentifier ski = util.createSubjectKeyIdentifier(x509Cert.getPublicKey());
    String b46Ski = Base64.encodeBase64String(ski.getKeyIdentifier());
    setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SKI, b46Ski);
    SubjectKeyIdentifier skiTruncated = util.createTruncatedSubjectKeyIdentifier(x509Cert.getPublicKey());
    if (!ski.equals(skiTruncated)) {
        setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SKI, Base64.encodeBase64String(skiTruncated.getKeyIdentifier()));
    }
    // add two serial variants
    setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SERIAL, serial);
    setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SERIAL_PADDED, getPaddedSerial(serial));
    // add validity period
    setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_VALID_FROM_TIMESTAMP, "" + x509Cert.getNotBefore().getTime());
    setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_VALID_TO_TIMESTAMP, "" + x509Cert.getNotAfter().getTime());
    long validityPeriod = (x509Cert.getNotAfter().getTime() - x509Cert.getNotBefore().getTime()) / 1000L;
    setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_VALIDITY_PERIOD, "" + validityPeriod);
    addAdditionalCertificateAttributes(x509Cert, cert);
    copyCsrAttributesToCertificate(csr, cert);
    certificateRepository.save(cert);
    certificateAttributeRepository.saveAll(cert.getCertificateAttributes());
    if (x500NameIssuer.equals(x500NameSubject)) {
        // check whether is really selfsigned
        x509Cert.verify(x509Cert.getPublicKey());
        // don't insert the self-reference. This leads to no good when JSON-serializing the object
        // The selfsigned-attribute will mark the fact!
        // cert.setIssuingCertificate(cert);
        // mark it as self signed
        cert.setSelfsigned(true);
        setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SELFSIGNED, "true");
        // don't build a self reference here
        cert.setIssuingCertificate(null);
        cert.setRootCertificate(null);
        cert.setRoot(cert.getSubject());
        setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ROOT, cert.getSubject().toLowerCase());
        LOG.debug("certificate '" + x509Cert.getSubjectX500Principal().getName() + "' is selfsigned");
    } else {
        // try to build cert chain
        try {
            Certificate issuingCert = findIssuingCertificate(x509CertHolder);
            if (issuingCert == null) {
                LOG.info("unable to find issuer for non-self-signed certificate '" + x509Cert.getSubjectX500Principal().getName() + "' right now ...");
            } else {
                cert.setIssuingCertificate(issuingCert);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("certificate '" + x509Cert.getSubjectX500Principal().getName() + "' issued by " + issuingCert.getSubject());
                }
            }
            Certificate rootCert = findRootCertificate(issuingCert);
            if (rootCert != null) {
                cert.setRootCertificate(rootCert);
                cert.setRoot(rootCert.getSubject());
                setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ROOT, rootCert.getSubject().toLowerCase());
            }
        } catch (GeneralSecurityException gse) {
            // LOG.debug("exception while retrieving issuer", gse);
            LOG.info("problem retrieving issuer for certificate '" + x509Cert.getSubjectX500Principal().getName() + "' right now ...");
        }
    }
    certificateRepository.save(cert);
    // LOG.debug("certificate id '" + cert.getId() +"' post-save");
    certificateAttributeRepository.saveAll(cert.getCertificateAttributes());
    LOG.debug("certificate id '{}' saved containing #{} attributes", cert.getId(), cert.getCertificateAttributes().size());
    for (CertificateAttribute cad : cert.getCertificateAttributes()) {
        LOG.debug("Name '" + cad.getName() + "' got value '" + cad.getValue() + "'");
    }
    final X509Principal principal = PrincipalUtil.getSubjectX509Principal(x509Cert);
    final Vector<?> values = principal.getValues(X509Name.CN);
    String cn = values.size() > 0 ? (String) values.get(0) : null;
    List<String> sanList = getCertAttributes(cert, CertificateAttribute.ATTRIBUTE_SAN);
    sanList.addAll(getCertAttributes(cert, CsrAttribute.ATTRIBUTE_TYPED_SAN));
    sanList.addAll(getCertAttributes(cert, CsrAttribute.ATTRIBUTE_TYPED_VSAN));
    List<Certificate> replacedCerts = findReplaceCandidates(Instant.now(), cn, sanList);
    if (replacedCerts.isEmpty()) {
        LOG.debug("certificate id {} does not replace any certificate", cert.getId());
    } else {
        for (Certificate replacedCert : replacedCerts) {
            if (!cert.equals(replacedCert)) {
                LOG.debug("certificate id {} replaces certificate id {}", cert.getId(), replacedCert.getId());
                setCertMultiValueAttribute(replacedCert, CertificateAttribute.ATTRIBUTE_REPLACED_BY, cert.getId().toString());
                certificateAttributeRepository.saveAll(replacedCert.getCertificateAttributes());
            }
        }
    }
    return cert;
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) GeneralSecurityException(java.security.GeneralSecurityException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Principal(org.bouncycastle.jce.X509Principal) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X509Certificate(java.security.cert.X509Certificate) Certificate(de.trustable.ca3s.core.domain.Certificate)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)510 X509Certificate (java.security.cert.X509Certificate)183 BigInteger (java.math.BigInteger)175 Date (java.util.Date)169 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)158 ContentSigner (org.bouncycastle.operator.ContentSigner)149 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)145 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)127 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)127 IOException (java.io.IOException)108 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)100 RDN (org.bouncycastle.asn1.x500.RDN)94 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)93 KeyPair (java.security.KeyPair)79 X500Name (sun.security.x509.X500Name)68 PrivateKey (java.security.PrivateKey)64 CertificateException (java.security.cert.CertificateException)64 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)59 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)55 GeneralName (org.bouncycastle.asn1.x509.GeneralName)55