use of com.github.zhenwei.core.asn1.pkcs.CertificationRequestInfo in project nhin-d by DirectProject.
the class CertGenerator method createCertFromCSR.
public static X509Certificate createCertFromCSR(PKCS10CertificationRequest certReq, CertCreateFields signerCert) throws Exception {
certReq.verify();
final CertificationRequestInfo reqInfo = certReq.getCertificationRequestInfo();
final X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
final Calendar start = Calendar.getInstance();
final Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 3);
v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
// issuer is the parent cert
v1CertGen.setIssuerDN(signerCert.getSignerCert().getSubjectX500Principal());
v1CertGen.setNotBefore(start.getTime());
v1CertGen.setNotAfter(end.getTime());
v1CertGen.setSubjectDN(new X509Principal(reqInfo.getSubject().toString()));
v1CertGen.setPublicKey(certReq.getPublicKey());
v1CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
final ASN1Set attributesAsn1Set = reqInfo.getAttributes();
X509Extensions certificateRequestExtensions = null;
for (int i = 0; i < attributesAsn1Set.size(); ++i) {
// There should be only only one attribute in the set. (that is, only
// the `Extension Request`, but loop through to find it properly)
final DEREncodable derEncodable = attributesAsn1Set.getObjectAt(i);
if (derEncodable instanceof DERSequence) {
final Attribute attribute = new Attribute((DERSequence) attributesAsn1Set.getObjectAt(i));
if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
// The `Extension Request` attribute is present.
final ASN1Set attributeValues = attribute.getAttrValues();
// Assume that it is the first value of the set.
if (attributeValues.size() >= 1) {
certificateRequestExtensions = new X509Extensions((ASN1Sequence) attributeValues.getObjectAt(0));
// No need to search any more.
//break;
}
}
}
}
@SuppressWarnings("unchecked") Enumeration<DERObjectIdentifier> oids = certificateRequestExtensions.oids();
while (oids.hasMoreElements()) {
DERObjectIdentifier oid = oids.nextElement();
X509Extension ex = certificateRequestExtensions.getExtension(oid);
v1CertGen.addExtension(oid, ex.isCritical(), X509Extension.convertValueToObject(ex));
}
return v1CertGen.generate((PrivateKey) signerCert.getSignerKey(), CryptoExtensions.getJCEProviderName());
}
use of com.github.zhenwei.core.asn1.pkcs.CertificationRequestInfo in project xipki by xipki.
the class X509CaCmpResponderImpl method processP10cr.
// method processCertReqMessages
/**
* handle the PKI body with the choice {@code p10cr}<br/>
* Since it is not possible to add attribute to the PKCS#10 request (CSR), the certificate
* profile must be specified in the attribute regInfo-utf8Pairs (1.3.6.1.5.5.7.5.2.1) within
* PKIHeader.generalInfo
*/
private PKIBody processP10cr(PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertificationRequest p10cr, CmpControl cmpControl, String msgId, AuditEvent event) {
// verify the POP first
CertResponse certResp;
ASN1Integer certReqId = new ASN1Integer(-1);
boolean certGenerated = false;
X509Ca ca = getCa();
if (!securityFactory.verifyPopo(p10cr, getCmpControl().getPopoAlgoValidator())) {
LOG.warn("could not validate POP for the pkcs#10 requst");
certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badPOP, "invalid POP");
} else {
CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
Extensions extensions = CaUtil.getExtensions(certTemp);
X500Name subject = certTemp.getSubject();
SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();
CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
String certprofileName = null;
Date notBefore = null;
Date notAfter = null;
if (keyvalues != null) {
certprofileName = keyvalues.value(CmpUtf8Pairs.KEY_CERTPROFILE);
String str = keyvalues.value(CmpUtf8Pairs.KEY_NOTBEFORE);
if (str != null) {
notBefore = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
}
str = keyvalues.value(CmpUtf8Pairs.KEY_NOTAFTER);
if (str != null) {
notAfter = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
}
}
if (certprofileName == null) {
certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badCertTemplate, "badCertTemplate", null);
} else {
certprofileName = certprofileName.toLowerCase();
if (!requestor.isCertProfilePermitted(certprofileName)) {
String msg = "certprofile " + certprofileName + " is not allowed";
certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.notAuthorized, msg);
} else {
CertTemplateData certTemplateData = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter, extensions, certprofileName);
certResp = generateCertificates(Arrays.asList(certTemplateData), Arrays.asList(certReqId), requestor, tid, false, request, cmpControl, msgId, event).get(0);
certGenerated = true;
}
}
}
CMPCertificate[] caPubs = null;
if (certGenerated && cmpControl.isSendCaCert()) {
caPubs = new CMPCertificate[] { ca.getCaInfo().getCertInCmpFormat() };
}
CertRepMessage repMessage = new CertRepMessage(caPubs, new CertResponse[] { certResp });
return new PKIBody(PKIBody.TYPE_CERT_REP, repMessage);
}
use of com.github.zhenwei.core.asn1.pkcs.CertificationRequestInfo 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 com.github.zhenwei.core.asn1.pkcs.CertificationRequestInfo in project jruby-openssl by jruby.
the class PKCS10Request method resetSignedRequest.
private void resetSignedRequest() {
if (signedRequest == null)
return;
CertificationRequest req = signedRequest.toASN1Structure();
CertificationRequestInfo reqInfo = new CertificationRequestInfo(subject, publicKeyInfo, req.getCertificationRequestInfo().getAttributes());
ASN1Sequence seq = (ASN1Sequence) req.toASN1Primitive();
req = new CertificationRequest(reqInfo, (AlgorithmIdentifier) seq.getObjectAt(1), (DERBitString) seq.getObjectAt(2));
// valid = true;
signedRequest = new PKCS10CertificationRequest(req);
}
use of com.github.zhenwei.core.asn1.pkcs.CertificationRequestInfo in project xipki by xipki.
the class CmpResponder method processP10cr.
// method processCertReqMessages
/**
* handle the PKI body with the choice {@code p10cr}<br/>
* Since it is not possible to add attribute to the PKCS#10 request (CSR), the certificate
* profile must be specified in the attribute regInfo-utf8Pairs (1.3.6.1.5.5.7.5.2.1) within
* PKIHeader.generalInfo
*/
private PKIBody processP10cr(String dfltCertprofileName, PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertificationRequest p10cr, CmpControl cmpControl, String msgId, AuditEvent event) {
// verify the POP first
CertResponse certResp = null;
ASN1Integer certReqId = new ASN1Integer(-1);
boolean certGenerated = false;
X509Ca ca = getCa();
if (!ca.verifyCsr(p10cr)) {
LOG.warn("could not validate POP for the pkcs#10 requst");
certResp = buildErrCertResp(certReqId, badPOP, "invalid POP");
} else {
CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
Extensions extensions;
try {
extensions = CaUtil.getExtensions(certTemp);
} catch (IllegalArgumentException ex) {
extensions = null;
LOG.warn("could not parse extensions of the pkcs#10 requst");
certResp = buildErrCertResp(certReqId, badCertTemplate, "invalid extensions");
}
if (certResp == null) {
X500Name subject = certTemp.getSubject();
SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();
InfoTypeAndValue[] generalInfo = reqHeader.getGeneralInfo();
CmpUtf8Pairs keyvalues = CmpUtil.extractUtf8Pairs(generalInfo);
// CertProfile name
String certprofileName = null;
String[] list = CmpUtil.extractCertProfile(generalInfo);
if (list != null && list.length > 0) {
certprofileName = list[0];
} else {
if (keyvalues != null) {
certprofileName = keyvalues.value(KEY_CERTPROFILE);
}
}
// NotBefore and NotAfter
Date notBefore = null;
Date notAfter = null;
if (keyvalues != null) {
String str = keyvalues.value(CmpUtf8Pairs.KEY_NOTBEFORE);
if (str != null) {
notBefore = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
}
str = keyvalues.value(CmpUtf8Pairs.KEY_NOTAFTER);
if (str != null) {
notAfter = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
}
}
if (certprofileName == null) {
certprofileName = dfltCertprofileName;
}
if (certprofileName == null) {
LOG.warn("no certprofile is specified");
certResp = buildErrCertResp(certReqId, badCertTemplate, "badCertTemplate");
} else {
certprofileName = certprofileName.toLowerCase();
if (!requestor.isCertprofilePermitted(certprofileName)) {
String msg = "certprofile " + certprofileName + " is not allowed";
certResp = buildErrCertResp(certReqId, notAuthorized, msg);
} else {
CertTemplateData certTemplateData = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter, extensions, certprofileName, certReqId, false);
certResp = generateCertificates(Collections.singletonList(certTemplateData), requestor, tid, false, request, cmpControl, msgId, event).get(0);
certGenerated = true;
}
}
}
}
CMPCertificate[] caPubs = null;
if (certGenerated && (cmpControl.isSendCaCert() || cmpControl.isSendCertChain())) {
List<CMPCertificate> certchain = new ArrayList<>(2);
certchain.add(getCa().getCaInfo().getCertInCmpFormat());
if (cmpControl.isSendCertChain()) {
certchain.addAll(getCa().getCaInfo().getCertchainInCmpFormat());
}
caPubs = certchain.toArray(new CMPCertificate[0]);
}
if (event.getStatus() == null || event.getStatus() != AuditStatus.FAILED) {
int status = certResp.getStatus().getStatus().intValue();
if (status != GRANTED && status != GRANTED_WITH_MODS && status != WAITING) {
event.setStatus(AuditStatus.FAILED);
PKIFreeText statusStr = certResp.getStatus().getStatusString();
if (statusStr != null) {
event.addEventData(CaAuditConstants.NAME_message, statusStr.getStringAt(0).getString());
}
}
}
return new PKIBody(PKIBody.TYPE_CERT_REP, new CertRepMessage(caPubs, new CertResponse[] { certResp }));
}
Aggregations