use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class XmlX509Certprofile method createRequestedSubjectAltNames.
private GeneralNames createRequestedSubjectAltNames(X500Name requestedSubject, X500Name grantedSubject, Extensions requestedExtensions) throws BadCertTemplateException {
ASN1Encodable extValue = (requestedExtensions == null) ? null : requestedExtensions.getExtensionParsedValue(Extension.subjectAlternativeName);
if (extValue == null && subjectToSubjectAltNameModes == null) {
return null;
}
GeneralNames reqNames = (extValue == null) ? null : GeneralNames.getInstance(extValue);
if (subjectAltNameModes == null && subjectToSubjectAltNameModes == null) {
return reqNames;
}
List<GeneralName> grantedNames = new LinkedList<>();
// copy the required attributes of Subject
if (subjectToSubjectAltNameModes != null) {
for (ASN1ObjectIdentifier attrType : subjectToSubjectAltNameModes.keySet()) {
GeneralNameTag tag = subjectToSubjectAltNameModes.get(attrType);
RDN[] rdns = grantedSubject.getRDNs(attrType);
if (rdns == null) {
rdns = requestedSubject.getRDNs(attrType);
}
if (rdns == null) {
continue;
}
for (RDN rdn : rdns) {
String rdnValue = X509Util.rdnValueToString(rdn.getFirst().getValue());
switch(tag) {
case rfc822Name:
case dNSName:
case uniformResourceIdentifier:
case iPAddress:
case directoryName:
case registeredID:
grantedNames.add(new GeneralName(tag.getTag(), rdnValue));
break;
default:
throw new RuntimeException("should not reach here, unknown GeneralName tag " + tag);
}
// end switch (tag)
}
}
}
// copy the requested SubjectAltName entries
if (reqNames != null) {
GeneralName[] reqL = reqNames.getNames();
for (int i = 0; i < reqL.length; i++) {
grantedNames.add(X509CertprofileUtil.createGeneralName(reqL[i], subjectAltNameModes));
}
}
return grantedNames.isEmpty() ? null : new GeneralNames(grantedNames.toArray(new GeneralName[0]));
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class X509CmpRequestor method buildUnrevokeOrRemoveCertRequest.
// method buildRevokeCertRequest
private PKIMessage buildUnrevokeOrRemoveCertRequest(UnrevokeOrRemoveCertRequest request, int reasonCode) throws CmpRequestorException {
PKIHeader header = buildPkiHeader(null);
List<UnrevokeOrRemoveCertEntry> requestEntries = request.getRequestEntries();
List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
for (UnrevokeOrRemoveCertEntry requestEntry : requestEntries) {
CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
certTempBuilder.setIssuer(requestEntry.getIssuer());
certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
byte[] aki = requestEntry.getAuthorityKeyIdentifier();
if (aki != null) {
Extensions certTempExts = getCertTempExtensions(aki);
certTempBuilder.setExtensions(certTempExts);
}
Extension[] extensions = new Extension[1];
try {
ASN1Enumerated reason = new ASN1Enumerated(reasonCode);
extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded()));
} catch (IOException ex) {
throw new CmpRequestorException(ex.getMessage(), ex);
}
Extensions exts = new Extensions(extensions);
RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
revDetailsArray.add(revDetails);
}
RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
return new PKIMessage(header, body);
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class OcspStatusCmd method processResponse.
@Override
protected Object processResponse(OCSPResp response, X509Certificate respIssuer, IssuerHash issuerHash, List<BigInteger> serialNumbers, Map<BigInteger, byte[]> encodedCerts) throws Exception {
ParamUtil.requireNonNull("response", response);
ParamUtil.requireNonNull("issuerHash", issuerHash);
ParamUtil.requireNonNull("serialNumbers", serialNumbers);
BasicOCSPResp basicResp = OcspUtils.extractBasicOcspResp(response);
boolean extendedRevoke = basicResp.getExtension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke) != null;
SingleResp[] singleResponses = basicResp.getResponses();
if (singleResponses == null || singleResponses.length == 0) {
throw new CmdFailure("received no status from server");
}
final int n = singleResponses.length;
if (n != serialNumbers.size()) {
throw new CmdFailure("received status with " + n + " single responses from server, but " + serialNumbers.size() + " were requested");
}
Date[] thisUpdates = new Date[n];
for (int i = 0; i < n; i++) {
thisUpdates[i] = singleResponses[i].getThisUpdate();
}
// check the signature if available
if (null == basicResp.getSignature()) {
println("response is not signed");
} else {
X509CertificateHolder[] responderCerts = basicResp.getCerts();
if (responderCerts == null || responderCerts.length < 1) {
throw new CmdFailure("no responder certificate is contained in the response");
}
ResponderID respId = basicResp.getResponderId().toASN1Primitive();
X500Name respIdByName = respId.getName();
byte[] respIdByKey = respId.getKeyHash();
X509CertificateHolder respSigner = null;
for (X509CertificateHolder cert : responderCerts) {
if (respIdByName != null) {
if (cert.getSubject().equals(respIdByName)) {
respSigner = cert;
}
} else {
byte[] spkiSha1 = HashAlgo.SHA1.hash(cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
if (Arrays.equals(respIdByKey, spkiSha1)) {
respSigner = cert;
}
}
if (respSigner != null) {
break;
}
}
if (respSigner == null) {
throw new CmdFailure("no responder certificate match the ResponderId");
}
boolean validOn = true;
for (Date thisUpdate : thisUpdates) {
validOn = respSigner.isValidOn(thisUpdate);
if (!validOn) {
throw new CmdFailure("responder certificate is not valid on " + thisUpdate);
}
}
if (validOn) {
PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(responderPubKey);
boolean sigValid = basicResp.isSignatureValid(cvp);
if (!sigValid) {
throw new CmdFailure("response is equipped with invalid signature");
}
// verify the OCSPResponse signer
if (respIssuer != null) {
boolean certValid = true;
X509Certificate jceRespSigner = X509Util.toX509Cert(respSigner.toASN1Structure());
if (X509Util.issues(respIssuer, jceRespSigner)) {
try {
jceRespSigner.verify(respIssuer.getPublicKey());
} catch (SignatureException ex) {
certValid = false;
}
}
if (!certValid) {
throw new CmdFailure("response is equipped with valid signature but the" + " OCSP signer is not trusted");
}
} else {
println("response is equipped with valid signature");
}
// end if(respIssuer)
}
if (verbose.booleanValue()) {
println("responder is " + X509Util.getRfc4519Name(responderCerts[0].getSubject()));
}
}
for (int i = 0; i < n; i++) {
if (n > 1) {
println("---------------------------- " + i + "----------------------------");
}
SingleResp singleResp = singleResponses[i];
CertificateStatus singleCertStatus = singleResp.getCertStatus();
String status;
if (singleCertStatus == null) {
status = "good";
} else if (singleCertStatus instanceof RevokedStatus) {
RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
Date revTime = revStatus.getRevocationTime();
Date invTime = null;
Extension ext = singleResp.getExtension(Extension.invalidityDate);
if (ext != null) {
invTime = ASN1GeneralizedTime.getInstance(ext.getParsedValue()).getDate();
}
if (revStatus.hasRevocationReason()) {
int reason = revStatus.getRevocationReason();
if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTime.getTime() == 0) {
status = "unknown (RFC6960)";
} else {
status = StringUtil.concatObjects("revoked, reason = ", CrlReason.forReasonCode(reason).getDescription(), ", revocationTime = ", revTime, (invTime == null ? "" : ", invalidityTime = " + invTime));
}
} else {
status = "revoked, no reason, revocationTime = " + revTime;
}
} else if (singleCertStatus instanceof UnknownStatus) {
status = "unknown (RFC2560)";
} else {
status = "ERROR";
}
StringBuilder msg = new StringBuilder();
CertificateID certId = singleResp.getCertID();
HashAlgo hashAlgo = HashAlgo.getNonNullInstance(certId.getHashAlgOID());
boolean issuerMatch = issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash());
BigInteger serialNumber = certId.getSerialNumber();
msg.append("issuer matched: ").append(issuerMatch);
msg.append("\nserialNumber: ").append(LogUtil.formatCsn(serialNumber));
msg.append("\nCertificate status: ").append(status);
if (verbose.booleanValue()) {
msg.append("\nthisUpdate: ").append(singleResp.getThisUpdate());
msg.append("\nnextUpdate: ").append(singleResp.getNextUpdate());
Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
if (extension != null) {
msg.append("\nCertHash is provided:\n");
ASN1Encodable extensionValue = extension.getParsedValue();
CertHash certHash = CertHash.getInstance(extensionValue);
ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
byte[] hashValue = certHash.getCertificateHash();
msg.append("\tHash algo : ").append(hashAlgOid.getId()).append("\n");
msg.append("\tHash value: ").append(Hex.encode(hashValue)).append("\n");
if (encodedCerts != null) {
byte[] encodedCert = encodedCerts.get(serialNumber);
MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
byte[] expectedHashValue = md.digest(encodedCert);
if (Arrays.equals(expectedHashValue, hashValue)) {
msg.append("\tThis matches the requested certificate");
} else {
msg.append("\tThis differs from the requested certificate");
}
}
}
// end if (extension != null)
extension = singleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
if (extension != null) {
ASN1Encodable extensionValue = extension.getParsedValue();
ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(extensionValue);
msg.append("\nArchive-CutOff: ");
msg.append(time.getTimeString());
}
AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
if (sigAlg == null) {
msg.append(("\nresponse is not signed"));
} else {
String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
if (sigAlgName == null) {
sigAlgName = "unknown";
}
msg.append("\nresponse is signed with ").append(sigAlgName);
}
// extensions
msg.append("\nExtensions: ");
List<?> extensionOids = basicResp.getExtensionOIDs();
if (extensionOids == null || extensionOids.size() == 0) {
msg.append("-");
} else {
int size = extensionOids.size();
for (int j = 0; j < size; j++) {
ASN1ObjectIdentifier extensionOid = (ASN1ObjectIdentifier) extensionOids.get(j);
String name = EXTENSION_OIDNAME_MAP.get(extensionOid);
if (name == null) {
msg.append(extensionOid.getId());
} else {
msg.append(name);
}
if (j != size - 1) {
msg.append(", ");
}
}
}
}
// end if (verbose.booleanValue())
println(msg.toString());
}
// end for
println("");
return null;
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class CheckCertCmd method execute0.
@Override
protected Object execute0() throws Exception {
Set<String> issuerNames = qaSystemManager.getIssuerNames();
if (isEmpty(issuerNames)) {
throw new IllegalCmdParamException("no issuer is configured");
}
if (issuerName == null) {
if (issuerNames.size() != 1) {
throw new IllegalCmdParamException("no issuer is specified");
}
issuerName = issuerNames.iterator().next();
}
if (!issuerNames.contains(issuerName)) {
throw new IllegalCmdParamException("issuer " + issuerName + " is not within the configured issuers " + issuerNames);
}
X509IssuerInfo issuerInfo = qaSystemManager.getIssuer(issuerName);
X509CertprofileQa qa = qaSystemManager.getCertprofile(profileName);
if (qa == null) {
throw new IllegalCmdParamException("found no certificate profile named '" + profileName + "'");
}
CertificationRequest csr = CertificationRequest.getInstance(IoUtil.read(csrFile));
Extensions extensions = null;
CertificationRequestInfo reqInfo = csr.getCertificationRequestInfo();
ASN1Set attrs = reqInfo.getAttributes();
for (int i = 0; i < attrs.size(); i++) {
Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
}
}
byte[] certBytes = IoUtil.read(certFile);
ValidationResult result = qa.checkCert(certBytes, issuerInfo, reqInfo.getSubject(), reqInfo.getSubjectPublicKeyInfo(), extensions);
StringBuilder sb = new StringBuilder();
sb.append(certFile).append(" (certprofile ").append(profileName).append(")\n");
sb.append("\tcertificate is ");
sb.append(result.isAllSuccessful() ? "valid" : "invalid");
if (verbose.booleanValue()) {
for (ValidationIssue issue : result.getValidationIssues()) {
sb.append("\n");
format(issue, " ", sb);
}
}
println(sb.toString());
if (!result.isAllSuccessful()) {
throw new CmdFailure("certificate is invalid");
}
return null;
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project candlepin by candlepin.
the class BouncyCastlePKIUtility method createX509Certificate.
@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {
X509Certificate caCert = reader.getCACert();
byte[] publicKeyEncoded = clientKeyPair.getPublic().getEncoded();
X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()), serialNumber, startDate, endDate, new X500Name(dn), SubjectPublicKeyInfo.getInstance(publicKeyEncoded));
// set key usage - required for proper x509 function
KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);
// add SSL extensions - required for proper x509 function
NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);
certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, certType);
certGen.addExtension(Extension.keyUsage, false, keyUsage);
JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
AuthorityKeyIdentifier aki = extensionUtil.createAuthorityKeyIdentifier(caCert);
certGen.addExtension(Extension.authorityKeyIdentifier, false, aki.getEncoded());
certGen.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
// Add an additional alternative name if provided.
if (alternateName != null) {
/*
Why add the certificate subject again as an alternative name? RFC 6125 Section 6.4.4
stipulates that if SANs are provided, a validator MUST use them instead of the certificate
subject. If no SANs are present, the RFC allows the validator to use the subject field. So,
if we do have an SAN to add, we need to add the subject field again as an SAN.
See http://stackoverflow.com/questions/5935369 and
https://tools.ietf.org/html/rfc6125#section-6.4.4 and
NB: These extensions should *not* be marked critical since the subject field is not empty.
*/
GeneralName subject = new GeneralName(GeneralName.directoryName, dn);
GeneralName name = new GeneralName(GeneralName.directoryName, "CN=" + alternateName);
ASN1Encodable[] altNameArray = { subject, name };
GeneralNames altNames = GeneralNames.getInstance(new DERSequence(altNameArray));
certGen.addExtension(Extension.subjectAlternativeName, false, altNames);
}
if (extensions != null) {
for (X509ExtensionWrapper wrapper : extensions) {
// Bouncycastle hates null values. So, set them to blank
// if they are null
String value = wrapper.getValue() == null ? "" : wrapper.getValue();
certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DERUTF8String(value));
}
}
if (byteExtensions != null) {
for (X509ByteExtensionWrapper wrapper : byteExtensions) {
// Bouncycastle hates null values. So, set them to blank
// if they are null
byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DEROctetString(value));
}
}
JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNATURE_ALGO).setProvider(BC_PROVIDER);
ContentSigner signer;
try {
signer = builder.build(reader.getCaKey());
} catch (OperatorCreationException e) {
throw new IOException(e);
}
// Generate the certificate
return new JcaX509CertificateConverter().getCertificate(certGen.build(signer));
}
Aggregations