Search in sources :

Example 36 with X500Name

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

the class CertificateUtil method insertNameAttributes.

/**
 * @param cert
 * @param attributeName
 * @param x500NameSubject
 */
public void insertNameAttributes(Certificate cert, String attributeName, X500Name x500NameSubject) {
    try {
        List<Rdn> rdnList = new LdapName(x500NameSubject.toString()).getRdns();
        for (Rdn rdn : rdnList) {
            String rdnExpression = rdn.getType().toLowerCase() + "=" + rdn.getValue().toString().toLowerCase().trim();
            setCertMultiValueAttribute(cert, attributeName, rdnExpression);
        }
    } catch (InvalidNameException e) {
        LOG.info("problem parsing RDN for {}", x500NameSubject);
    }
    for (RDN rdn : x500NameSubject.getRDNs()) {
        for (org.bouncycastle.asn1.x500.AttributeTypeAndValue atv : rdn.getTypesAndValues()) {
            String value = atv.getValue().toString().toLowerCase().trim();
            setCertMultiValueAttribute(cert, attributeName, value);
            String oid = atv.getType().getId().toLowerCase();
            setCertMultiValueAttribute(cert, attributeName, oid + "=" + value);
            if (!oid.equals(atv.getType().toString().toLowerCase())) {
                setCertMultiValueAttribute(cert, attributeName, atv.getType().toString().toLowerCase() + "=" + value);
            }
        }
    }
}
Also used : AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue) InvalidNameException(javax.naming.InvalidNameException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) Rdn(javax.naming.ldap.Rdn) RDN(org.bouncycastle.asn1.x500.RDN) LdapName(javax.naming.ldap.LdapName)

Example 37 with X500Name

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

the class CertificateUtil method addAdditionalCertificateAttributes.

/**
 * @param x509Cert
 * @param cert
 * @throws CertificateParsingException
 * @throws IOException
 */
public void addAdditionalCertificateAttributes(X509Certificate x509Cert, Certificate cert) throws CertificateParsingException, IOException {
    int version = Integer.parseInt(getCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ATTRIBUTES_VERSION, "0"));
    if (version == 0) {
        // extract signature algo
        String keyAlgName = x509Cert.getPublicKey().getAlgorithm();
        cert.setKeyAlgorithm(keyAlgName.toLowerCase());
        AlgorithmInfo algorithmInfo = new AlgorithmInfo(x509Cert.getSigAlgName());
        cert.setHashingAlgorithm(algorithmInfo.getHashAlgName());
        cert.setPaddingAlgorithm(algorithmInfo.getPaddingAlgName());
        cert.setSigningAlgorithm(algorithmInfo.getSigAlgName());
        try {
            String curveName = deriveCurveName(x509Cert.getPublicKey());
            LOG.info("found curve name " + curveName + " for certificate '" + x509Cert.getSubjectX500Principal().getName() + "' with key algo " + keyAlgName);
            cert.setCurveName(curveName.toLowerCase());
        } catch (GeneralSecurityException e) {
            if (keyAlgName.contains("ec")) {
                LOG.info("unable to derive curve name for certificate '" + x509Cert.getSubjectX500Principal().getName() + "' with key algo " + keyAlgName);
            }
        }
        String subject = x509Cert.getSubjectX500Principal().getName();
        if (subject != null && subject.trim().length() > 0) {
            try {
                InetAddressValidator inv = InetAddressValidator.getInstance();
                List<Rdn> rdnList = new LdapName(subject).getRdns();
                for (Rdn rdn : rdnList) {
                    if ("CN".equalsIgnoreCase(rdn.getType())) {
                        String cn = rdn.getValue().toString();
                        if (inv.isValid(cn)) {
                            LOG.debug("CN found IP in subject: '{}'", cn);
                            setCertMultiValueAttribute(cert, CsrAttribute.ATTRIBUTE_TYPED_VSAN, "IP:" + cn);
                        } else {
                            LOG.debug("CN found DNS name in subject: '{}'", cn);
                            setCertMultiValueAttribute(cert, CsrAttribute.ATTRIBUTE_TYPED_VSAN, "DNS:" + cn);
                        }
                    }
                }
            } catch (InvalidNameException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        String allSans = "";
        // list all SANs
        if (x509Cert.getSubjectAlternativeNames() != null) {
            Collection<List<?>> altNames = x509Cert.getSubjectAlternativeNames();
            if (altNames != null) {
                for (List<?> altName : altNames) {
                    int altNameType = (Integer) altName.get(0);
                    String sanValue = "";
                    if (altName.get(1) instanceof String) {
                        sanValue = ((String) altName.get(1)).toLowerCase();
                    } else if (GeneralName.otherName == altNameType) {
                    // sanValue = "--other value--";
                    } else if (altName.get(1) instanceof byte[]) {
                        sanValue = new String((byte[]) (altName.get(1))).toLowerCase();
                    } else {
                        LOG.info("unexpected content type in SANS : {}", altName.get(1).toString());
                    }
                    if (allSans.length() > 0) {
                        allSans += ";";
                    }
                    allSans += sanValue;
                    setCertMultiValueAttribute(cert, CertificateAttribute.ATTRIBUTE_SAN, sanValue);
                    setCertMultiValueAttribute(cert, CsrAttribute.ATTRIBUTE_TYPED_SAN, getTypedSAN(altNameType, sanValue));
                }
            }
        }
        cert.setSans(CryptoUtil.limitLength(allSans, 250));
        int keyLength = getAlignedKeyLength(x509Cert.getPublicKey());
        cert.setKeyLength(keyLength);
        List<String> crlUrls = getCrlDistributionPoints(x509Cert);
        for (String crlUrl : crlUrls) {
            setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_CRL_URL, crlUrl);
        }
        String ocspUrl = getOCSPUrl(x509Cert);
        if (ocspUrl != null) {
            setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_OCSP_URL, ocspUrl);
        }
        List<String> certificatePolicyIds = getCertificatePolicies(x509Cert);
        for (String polId : certificatePolicyIds) {
            setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_POLICY_ID, polId);
        }
    }
    if (version < 2) {
        try {
            setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_FINGERPRINT_SHA1, DigestUtils.sha1Hex(x509Cert.getEncoded()).toLowerCase());
            setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_FINGERPRINT_SHA256, DigestUtils.sha3_256Hex(x509Cert.getEncoded()).toLowerCase());
        } catch (CertificateEncodingException e) {
            LOG.error("Problem getting encoded certificate '" + x509Cert.getSubjectX500Principal().getName() + "'", e);
        }
        try {
            if (!cert.getSubject().trim().isEmpty()) {
                X500Name x500Name = new X500Name(cert.getSubject());
                for (RDN rdn : x500Name.getRDNs()) {
                    AttributeTypeAndValue[] attrTVArr = rdn.getTypesAndValues();
                    for (AttributeTypeAndValue attrTV : attrTVArr) {
                        String rdnReadableName = OidNameMapper.lookupOid(attrTV.getType().toString());
                        setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_RDN_PREFIX + rdnReadableName.toUpperCase(), attrTV.getValue().toString());
                    }
                }
            }
        } catch (IllegalArgumentException iae) {
            LOG.error("Problem building X500Name for subject for certificate '" + x509Cert.getSubjectX500Principal().getName() + "'", iae);
        }
    }
    if (version < CURRENT_ATTRIBUTES_VERSION) {
        try {
            String subjectRfc2253 = getNormalizedName(cert.getSubject());
            setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_SUBJECT_RFC_2253, subjectRfc2253, false);
        } catch (InvalidNameException e) {
            LOG.error("Problem building RFC 2253-styled subject for  certificate '" + x509Cert.getSubjectX500Principal().getName() + "'", e);
        }
        setCertAttribute(cert, CertificateAttribute.ATTRIBUTE_ATTRIBUTES_VERSION, "" + CURRENT_ATTRIBUTES_VERSION, false);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) AlgorithmInfo(de.trustable.util.AlgorithmInfo) CertificateEncodingException(java.security.cert.CertificateEncodingException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) InetAddressValidator(org.apache.commons.validator.routines.InetAddressValidator) X500Name(org.bouncycastle.asn1.x500.X500Name) AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue) LdapName(javax.naming.ldap.LdapName) InvalidNameException(javax.naming.InvalidNameException) Rdn(javax.naming.ldap.Rdn) RDN(org.bouncycastle.asn1.x500.RDN)

Example 38 with X500Name

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

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

the class CaInternalConnector method createNewIntermediate.

private Certificate createNewIntermediate(Certificate root) throws GeneralSecurityException, IOException {
    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    X500Name subject = new X500Name("CN=CA3S-Intermediate" + System.currentTimeMillis() + ", OU=Internal Only, OU=Dev/Test Only, O=trustable solutions, C=DE");
    PrivateKey privKeyRoot = certUtil.getPrivateKey(root);
    KeyPair kpRoot = new KeyPair(certUtil.convertPemToCertificate(root.getContent()).getPublicKey(), privKeyRoot);
    X509Certificate x509Cert = cryptoUtil.issueCertificate(new X500Name(root.getSubject()), kpRoot, subject, keyPair.getPublic().getEncoded(), Calendar.YEAR, 1, PKILevel.INTERMEDIATE);
    Certificate intermediateCert = certUtil.createCertificate(x509Cert.getEncoded(), null, "", false);
    certUtil.storePrivateKey(intermediateCert, keyPair);
    certUtil.setCertAttribute(intermediateCert, CertificateAttribute.ATTRIBUTE_CA3S_INTERMEDIATE, "true");
    certRepository.save(intermediateCert);
    return intermediateCert;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(de.trustable.ca3s.core.domain.Certificate)

Example 40 with X500Name

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

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