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);
}
}
}
}
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);
}
}
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());
*/
}
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;
}
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));
}
Aggregations