use of org.bouncycastle.asn1.x509 in project ca3sCore by kuehne-trustable-de.
the class CSRUtil method buildCSR.
/**
* @param csrBase64
* @param p10ReqHolder
* @param pipelineType
* @return
* @throws IOException
*/
public CSR buildCSR(final String csrBase64, String requestorName, final Pkcs10RequestHolder p10ReqHolder, PipelineType pipelineType, Pipeline pipeline) throws IOException {
CSR csr = new CSR();
csr.setStatus(CsrStatus.PENDING);
csr.setPipeline(pipeline);
csr.setPipelineType(pipelineType);
// avoid to forward the initial CSR text: don't store accidentially included private keys or XSS attacks
// csr.setCsrBase64(csrBase64);
csr.setCsrBase64(CryptoUtil.pkcs10RequestToPem(p10ReqHolder.getP10Req()));
csr.setSubject(p10ReqHolder.getSubject());
/**
* produce a readable form of algorithms
*/
String sigAlgName = OidNameMapper.lookupOid(p10ReqHolder.getSigningAlgorithm());
String keyAlgName = getKeyAlgoName(sigAlgName);
csr.setSigningAlgorithm(sigAlgName);
csr.setIsCSRValid(p10ReqHolder.isCSRValid());
csr.setx509KeySpec(p10ReqHolder.getX509KeySpec());
csr.setPublicKeyAlgorithm(keyAlgName);
csr.setPublicKeyHash(p10ReqHolder.getPublicKeyHash());
csr.setKeyLength(CertificateUtil.getAlignedKeyLength(p10ReqHolder.getPublicSigningKey()));
csr.setServersideKeyGeneration(false);
csr.setSubjectPublicKeyInfoBase64(p10ReqHolder.getSubjectPublicKeyInfoBase64());
/*
* if( p10ReqHolder.publicSigningKey != null ){ try {
* this.setPublicKeyPEM(cryptoUtil.publicKeyToPem(
* p10ReqHolder.publicSigningKey)); } catch (IOException e) {
* logger.warn("wrapping of public key into PEM failed."); } }
*/
// not yet ...
// setProcessInstanceId(processInstanceId);
csr.setRequestedOn(Instant.now());
csr.setRequestedBy(requestorName);
csrRepository.save(csr);
AlgorithmInfo algorithmInfo = p10ReqHolder.getAlgorithmInfo();
setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_HASH_ALGO, algorithmInfo.getHashAlgName(), false);
setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_SIGN_ALGO, algorithmInfo.getSigAlgName(), false);
setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_PADDING_ALGO, algorithmInfo.getPaddingAlgName(), false);
if (algorithmInfo.getMfgName() != null && !algorithmInfo.getMfgName().isEmpty()) {
setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_MFG, algorithmInfo.getMfgName(), false);
}
LOG.debug("RDN arr #" + p10ReqHolder.getSubjectRDNs().length);
Set<RDN> newRdns = new HashSet<>();
for (org.bouncycastle.asn1.x500.RDN currentRdn : p10ReqHolder.getSubjectRDNs()) {
RDN rdn = new RDN();
rdn.csr(csr);
LOG.debug("AttributeTypeAndValue arr #" + currentRdn.size());
Set<RDNAttribute> rdnAttributes = new HashSet<>();
AttributeTypeAndValue[] attrTVArr = currentRdn.getTypesAndValues();
for (AttributeTypeAndValue attrTV : attrTVArr) {
RDNAttribute rdnAttr = new RDNAttribute();
rdnAttr.setRdn(rdn);
rdnAttr.setAttributeType(attrTV.getType().toString());
rdnAttr.setAttributeValue(attrTV.getValue().toString());
rdnAttributes.add(rdnAttr);
}
rdn.setRdnAttributes(rdnAttributes);
newRdns.add(rdn);
}
try {
insertNameAttributes(csr, CsrAttribute.ATTRIBUTE_SUBJECT, new LdapName(p10ReqHolder.getSubject()));
} catch (InvalidNameException e) {
LOG.info("problem parsing RDN for {}", p10ReqHolder.getSubject());
}
insertNameAttributes(csr, CsrAttribute.ATTRIBUTE_SUBJECT, p10ReqHolder.getSubjectRDNs());
Set<GeneralName> gNameSet = getSANList(p10ReqHolder);
String allSans = "";
LOG.debug("putting SANs into CSRAttributes");
for (GeneralName gName : gNameSet) {
String sanValue = gName.getName().toString();
if (GeneralName.otherName == gName.getTagNo()) {
sanValue = "--other value--";
}
if (allSans.length() > 0) {
allSans += ";";
}
allSans += sanValue;
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_SAN, sanValue, true);
if (GeneralName.dNSName == gName.getTagNo()) {
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_TYPED_SAN, "DNS:" + sanValue, true);
} else if (GeneralName.iPAddress == gName.getTagNo()) {
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_TYPED_SAN, "IP:" + sanValue, true);
} else if (GeneralName.ediPartyName == gName.getTagNo()) {
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_TYPED_SAN, "EDI:" + sanValue, true);
} else if (GeneralName.otherName == gName.getTagNo()) {
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_TYPED_SAN, "other:" + sanValue, true);
} else if (GeneralName.registeredID == gName.getTagNo()) {
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_TYPED_SAN, "regID:" + sanValue, true);
} else if (GeneralName.rfc822Name == gName.getTagNo()) {
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_TYPED_SAN, "rfc822:" + sanValue, true);
} else if (GeneralName.uniformResourceIdentifier == gName.getTagNo()) {
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_TYPED_SAN, "URI:" + sanValue, true);
} else if (GeneralName.x400Address == gName.getTagNo()) {
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_TYPED_SAN, "X400:" + sanValue, true);
} else if (GeneralName.directoryName == gName.getTagNo()) {
this.setCsrAttribute(csr, CsrAttribute.ATTRIBUTE_TYPED_SAN, "DirName:" + sanValue, true);
} else {
LOG.info("unexpected name / tag '{}' in SANs", gName.getTagNo());
}
}
csr.setSans(CryptoUtil.limitLength(allSans, 250));
if (p10ReqHolder.getSubjectRDNs().length == 0) {
LOG.info("Subject empty, using SANs");
for (GeneralName gName : gNameSet) {
if (GeneralName.dNSName == gName.getTagNo()) {
RDN rdn = new RDN();
rdn.csr(csr);
Set<RDNAttribute> rdnAttributes = new HashSet<>();
RDNAttribute rdnAttr = new RDNAttribute();
rdnAttr.setRdn(rdn);
rdnAttr.setAttributeType(X509ObjectIdentifiers.commonName.toString());
rdnAttr.setAttributeValue(gName.getName().toString());
rdnAttributes.add(rdnAttr);
rdn.setRdnAttributes(rdnAttributes);
newRdns.add(rdn);
LOG.info("First DNS SAN inserted as CN: " + gName.getName().toString());
// just one CN !
break;
}
}
}
csr.setRdns(newRdns);
Set<RequestAttribute> newRas = new HashSet<>();
for (Attribute attr : p10ReqHolder.getReqAttributes()) {
RequestAttribute reqAttrs = new RequestAttribute();
reqAttrs.setCsr(csr);
reqAttrs.setAttributeType(attr.getAttrType().toString());
Set<RequestAttributeValue> requestAttributes = new HashSet<>();
String type = attr.getAttrType().toString();
ASN1Set valueSet = attr.getAttrValues();
LOG.debug("AttributeSet type " + type + " #" + valueSet.size());
for (ASN1Encodable asn1Enc : valueSet.toArray()) {
String value = asn1Enc.toString();
LOG.debug("Attribute value " + value);
RequestAttributeValue reqAttrValue = new RequestAttributeValue();
reqAttrValue.setReqAttr(reqAttrs);
reqAttrValue.setAttributeValue(asn1Enc.toString());
requestAttributes.add(reqAttrValue);
}
reqAttrs.setRequestAttributeValues(requestAttributes);
newRas.add(reqAttrs);
}
csr.setRas(newRas);
// add requestor
CsrAttribute csrAttRequestorName = new CsrAttribute();
csrAttRequestorName.setCsr(csr);
csrAttRequestorName.setName(CsrAttribute.ATTRIBUTE_REQUESTED_BY);
csrAttRequestorName.setValue(requestorName);
csr.getCsrAttributes().add(csrAttRequestorName);
rdnRepository.saveAll(csr.getRdns());
for (RDN rdn : csr.getRdns()) {
rdnAttRepository.saveAll(rdn.getRdnAttributes());
}
/*
rasRepository.saveAll(csr.getRas());
for( RequestAttribute ras: csr.getRas()) {
rasvRepository.saveAll(ras.getRequestAttributeValues());
}
*/
csrAttRepository.saveAll(csr.getCsrAttributes());
csrRepository.save(csr);
LOG.debug("saved #{} csr attributes, ", newRas.size());
return csr;
}
use of org.bouncycastle.asn1.x509 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 org.bouncycastle.asn1.x509 in project conformance-suite by openid-certification.
the class ValidateMTLSCertificatesAsX509 method verifyECPrivateKey.
private void verifyECPrivateKey(String certString, String keyString, byte[] decodedKey, X509Certificate certificate) {
PrivateKey privateKey;
try {
// try to generate private key is PKCS8
KeySpec kspec = new PKCS8EncodedKeySpec(decodedKey);
privateKey = KeyFactory.getInstance("EC", "BC").generatePrivate(kspec);
} catch (InvalidKeySpecException e) {
try {
// try to generate private key isn't PKCS8
ASN1Sequence seq = ASN1Sequence.getInstance(decodedKey);
org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
byte[] server_pkcs8 = new PrivateKeyInfo(algId, pKey).getEncoded();
privateKey = KeyFactory.getInstance("EC", "BC").generatePrivate(new PKCS8EncodedKeySpec(server_pkcs8));
} catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException ex) {
throw error("Couldn't generate private key", e, args("key", keyString));
}
} catch (NoSuchProviderException | NoSuchAlgorithmException e) {
throw error("Provider or Algorithm of KeyFactory is invalid", e);
}
// TODO: Need to check that the private key and the certificate match
// This check isn't sure yet
ECPublicKey ecPublicKey = (ECPublicKey) certificate.getPublicKey();
if (!((ECPrivateKey) privateKey).getParameters().equals(ecPublicKey.getParameters())) {
throw error("MTLS Private Key and Cert do not match", args("cert", certString, "key", keyString));
}
}
use of org.bouncycastle.asn1.x509 in project conformance-suite by openid-certification.
the class GenerateFakeMTLSCertificate method evaluate.
@Override
@PreEnvironment(required = "mutual_tls_authentication")
@PostEnvironment(required = "fake_mutual_tls_authentication")
public Environment evaluate(Environment env) {
var extensionOidsNotToCopy = new HashSet<String>();
KeyPairGenerator generator;
try {
generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
} catch (NoSuchAlgorithmException e) {
throw error(e.getMessage(), e);
}
KeyPair kp = generator.generateKeyPair();
KeyPair cakp = generator.generateKeyPair();
PublicKey newPubKey = kp.getPublic();
String certString = env.getString("mutual_tls_authentication", "cert");
X509Certificate originalCert = generateCertificateFromMTLSCert(certString);
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
v3CertGen.setSubjectDN(originalCert.getSubjectX500Principal());
v3CertGen.setSignatureAlgorithm(originalCert.getSigAlgName());
v3CertGen.setPublicKey(newPubKey);
v3CertGen.setNotAfter(originalCert.getNotAfter());
v3CertGen.setNotBefore(originalCert.getNotBefore());
v3CertGen.setIssuerDN(originalCert.getIssuerX500Principal());
v3CertGen.setSerialNumber(originalCert.getSerialNumber());
// copy other extensions:
Set<String> critExts = originalCert.getCriticalExtensionOIDs();
try {
if (critExts != null) {
for (String oid : critExts) {
if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid)) {
v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), true, originalCert);
}
}
}
Set<String> nonCritExs = originalCert.getNonCriticalExtensionOIDs();
if (nonCritExs != null) {
for (String oid : nonCritExs) {
if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid)) {
v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), false, originalCert);
}
}
}
} catch (CertificateParsingException e) {
throw error("x509 copyAndAddExtension failed", e);
}
JcaX509ExtensionUtils jcaX509ExtensionUtils = null;
try {
jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
} catch (NoSuchAlgorithmException e) {
throw error("JcaX509ExtensionUtils failed", e);
}
v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false, jcaX509ExtensionUtils.createSubjectKeyIdentifier(newPubKey));
X509Certificate cert;
try {
v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(cakp.getPublic()));
var caPrivateKey = cakp.getPrivate();
cert = v3CertGen.generate(caPrivateKey, "BC");
} catch (CertificateEncodingException | NoSuchProviderException | NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
throw error("cert.generate failed", e);
}
JsonObject mtls = new JsonObject();
try {
mtls.addProperty("cert", Base64.getEncoder().encodeToString(cert.getEncoded()));
} catch (CertificateEncodingException e) {
throw error("Error encoding certificate", e);
}
mtls.addProperty("key", Base64.getEncoder().encodeToString(kp.getPrivate().getEncoded()));
env.putObject("fake_mutual_tls_authentication", mtls);
// we could add a ca cert too perhaps
logSuccess("Generated our own client MTLS certificate based on the supplied one", args("fake_mutual_tls_authentication", mtls));
return env;
}
use of org.bouncycastle.asn1.x509 in project uaa by cloudfoundry.
the class RsaJsonWebKeyTests method parseKeyPair.
private KeyPair parseKeyPair(String pemData) {
Matcher m = PEM_DATA.matcher(pemData.trim());
if (!m.matches()) {
throw new IllegalArgumentException("String is not PEM encoded data");
}
String type = m.group(1);
final byte[] content = b64Decode(utf8Encode(m.group(2)));
PublicKey publicKey;
PrivateKey privateKey = null;
try {
KeyFactory fact = KeyFactory.getInstance("RSA");
if (type.equals("RSA PRIVATE KEY")) {
ASN1Sequence seq = ASN1Sequence.getInstance(content);
if (seq.size() != 9) {
throw new IllegalArgumentException("Invalid RSA Private Key ASN1 sequence.");
}
org.bouncycastle.asn1.pkcs.RSAPrivateKey key = org.bouncycastle.asn1.pkcs.RSAPrivateKey.getInstance(seq);
RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(key.getModulus(), key.getPublicExponent(), key.getPrivateExponent(), key.getPrime1(), key.getPrime2(), key.getExponent1(), key.getExponent2(), key.getCoefficient());
publicKey = fact.generatePublic(pubSpec);
privateKey = fact.generatePrivate(privSpec);
} else if (type.equals("PUBLIC KEY")) {
KeySpec keySpec = new X509EncodedKeySpec(content);
publicKey = fact.generatePublic(keySpec);
} else if (type.equals("RSA PUBLIC KEY")) {
ASN1Sequence seq = ASN1Sequence.getInstance(content);
org.bouncycastle.asn1.pkcs.RSAPublicKey key = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(seq);
RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
publicKey = fact.generatePublic(pubSpec);
} else {
throw new IllegalArgumentException(type + " is not a supported format");
}
return new KeyPair(publicKey, privateKey);
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
Aggregations