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