use of org.openecard.bouncycastle.asn1.x509.Extensions in project keystore-explorer by kaikramer.
the class Pkcs10Util method generateCsr.
/**
* Create a PKCS #10 certificate signing request (CSR) using the supplied
* certificate, private key and signature algorithm.
*
* @param cert
* The certificate
* @param privateKey
* The private key
* @param signatureType
* Signature
* @param challenge
* Challenge, optional, pass null if not required
* @param unstructuredName
* An optional company name, pass null if not required
* @param useExtensions
* Use extensions from cert for extensionRequest attribute?
* @throws CryptoException
* If there was a problem generating the CSR
* @return The CSR
*/
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException {
try {
JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(cert.getSubjectX500Principal(), cert.getPublicKey());
// add challenge attribute
if (challenge != null) {
// PKCS#9 2.0: SHOULD use UTF8String encoding
csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
}
if (unstructuredName != null) {
csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
}
if (useExtensions) {
// add extensionRequest attribute with all extensions from the certificate
Certificate certificate = Certificate.getInstance(cert.getEncoded());
Extensions extensions = certificate.getTBSCertificate().getExtensions();
if (extensions != null) {
csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
}
}
// fall back to bouncy castle provider if given provider does not support the requested algorithm
if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
provider = new BouncyCastleProvider();
}
ContentSigner contentSigner = null;
if (provider == null) {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
} else {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider).build(privateKey);
}
PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);
if (!verifyCsr(csr)) {
throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
}
return csr;
} catch (CertificateEncodingException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
} catch (OperatorCreationException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
}
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class X509SelfSignedCertBuilder method generateCertificate.
// method generateSelfSigned
private static X509Certificate generateCertificate(ConcurrentContentSigner signer, IdentifiedX509Certprofile certprofile, CertificationRequest csr, BigInteger serialNumber, SubjectPublicKeyInfo publicKeyInfo, List<String> caCertUris, List<String> ocspUris, List<String> crlUris, List<String> deltaCrlUris, ConfPairs extraControl) throws OperationException {
SubjectPublicKeyInfo tmpPublicKeyInfo;
try {
tmpPublicKeyInfo = X509Util.toRfc3279Style(publicKeyInfo);
} catch (InvalidKeySpecException ex) {
LOG.warn("SecurityUtil.toRfc3279Style", ex);
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
try {
certprofile.checkPublicKey(tmpPublicKeyInfo);
} catch (BadCertTemplateException ex) {
LOG.warn("certprofile.checkPublicKey", ex);
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
X500Name requestedSubject = csr.getCertificationRequestInfo().getSubject();
SubjectInfo subjectInfo;
// subject
try {
subjectInfo = certprofile.getSubject(requestedSubject);
} catch (CertprofileException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofile.getIdent());
} catch (BadCertTemplateException ex) {
LOG.warn("certprofile.getSubject", ex);
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
Date notBefore = certprofile.getNotBefore(null);
if (notBefore == null) {
notBefore = new Date();
}
CertValidity validity = certprofile.getValidity();
if (validity == null) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "no validity specified in the profile " + certprofile.getIdent());
}
Date notAfter = validity.add(notBefore);
X500Name grantedSubject = subjectInfo.getGrantedSubject();
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(grantedSubject, serialNumber, notBefore, notAfter, grantedSubject, tmpPublicKeyInfo);
PublicCaInfo publicCaInfo = new PublicCaInfo(grantedSubject, serialNumber, null, null, caCertUris, ocspUris, crlUris, deltaCrlUris, extraControl);
Extensions extensions = null;
ASN1Set attrs = csr.getCertificationRequestInfo().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]);
}
}
try {
addExtensions(certBuilder, certprofile, requestedSubject, grantedSubject, extensions, tmpPublicKeyInfo, publicCaInfo, notBefore, notAfter);
ConcurrentBagEntrySigner signer0 = signer.borrowSigner();
X509CertificateHolder certHolder;
try {
certHolder = certBuilder.build(signer0.value());
} finally {
signer.requiteSigner(signer0);
}
Certificate bcCert = certHolder.toASN1Structure();
return X509Util.parseCert(bcCert.getEncoded());
} catch (BadCertTemplateException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
} catch (NoIdleSignerException | CertificateException | IOException | CertprofileException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
}
}
use of org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class X509CaCmpResponderImpl method cmpUnRevokeRemoveCertificates.
// method cmpEnrollCert
private PKIBody cmpUnRevokeRemoveCertificates(PKIMessage request, PKIHeaderBuilder respHeader, CmpControl cmpControl, PKIHeader reqHeader, PKIBody reqBody, CmpRequestorInfo requestor, String msgId, AuditEvent event) {
Integer requiredPermission = null;
boolean allRevdetailsOfSameType = true;
RevReqContent rr = RevReqContent.getInstance(reqBody.getContent());
RevDetails[] revContent = rr.toRevDetailsArray();
int len = revContent.length;
for (int i = 0; i < len; i++) {
RevDetails revDetails = revContent[i];
Extensions crlDetails = revDetails.getCrlEntryDetails();
int reasonCode = CrlReason.UNSPECIFIED.getCode();
if (crlDetails != null) {
ASN1ObjectIdentifier extId = Extension.reasonCode;
ASN1Encodable extValue = crlDetails.getExtensionParsedValue(extId);
if (extValue != null) {
reasonCode = ASN1Enumerated.getInstance(extValue).getValue().intValue();
}
}
if (reasonCode == XiSecurityConstants.CMP_CRL_REASON_REMOVE) {
if (requiredPermission == null) {
event.addEventType(CaAuditConstants.TYPE_CMP_rr_remove);
requiredPermission = PermissionConstants.REMOVE_CERT;
} else if (requiredPermission != PermissionConstants.REMOVE_CERT) {
allRevdetailsOfSameType = false;
break;
}
} else if (reasonCode == CrlReason.REMOVE_FROM_CRL.getCode()) {
if (requiredPermission == null) {
event.addEventType(CaAuditConstants.TYPE_CMP_rr_unrevoke);
requiredPermission = PermissionConstants.UNREVOKE_CERT;
} else if (requiredPermission != PermissionConstants.UNREVOKE_CERT) {
allRevdetailsOfSameType = false;
break;
}
} else {
if (requiredPermission == null) {
event.addEventType(CaAuditConstants.TYPE_CMP_rr_revoke);
requiredPermission = PermissionConstants.REVOKE_CERT;
} else if (requiredPermission != PermissionConstants.REVOKE_CERT) {
allRevdetailsOfSameType = false;
break;
}
}
}
if (!allRevdetailsOfSameType) {
ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText("not all revDetails are of the same type"), new PKIFailureInfo(PKIFailureInfo.badRequest)));
return new PKIBody(PKIBody.TYPE_ERROR, emc);
} else {
try {
checkPermission(requestor, requiredPermission);
} catch (InsuffientPermissionException ex) {
event.setStatus(AuditStatus.FAILED);
event.addEventData(CaAuditConstants.NAME_message, "NOT_PERMITTED");
return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.notAuthorized, null);
}
return unRevokeRemoveCertificates(request, rr, requiredPermission, cmpControl, msgId);
}
}
use of org.openecard.bouncycastle.asn1.x509.Extensions 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 org.openecard.bouncycastle.asn1.x509.Extensions in project xipki by xipki.
the class ExtensionsChecker method checkExtensionBiometricInfo.
// method checkExtensionQcStatements
private void checkExtensionBiometricInfo(StringBuilder failureMsg, byte[] extensionValue, Extensions requestedExtensions, ExtensionControl extControl) {
BiometricInfoOption conf = certProfile.getBiometricInfo();
if (conf == null) {
failureMsg.append("extension is present but not expected; ");
return;
}
ASN1Encodable extInRequest = null;
if (requestedExtensions != null) {
extInRequest = requestedExtensions.getExtensionParsedValue(Extension.biometricInfo);
}
if (extInRequest == null) {
failureMsg.append("extension is present but not expected; ");
return;
}
ASN1Sequence extValueInReq = ASN1Sequence.getInstance(extInRequest);
final int expSize = extValueInReq.size();
ASN1Sequence extValue = ASN1Sequence.getInstance(extensionValue);
final int isSize = extValue.size();
if (isSize != expSize) {
addViolation(failureMsg, "number of biometricData", isSize, expSize);
return;
}
for (int i = 0; i < expSize; i++) {
BiometricData isData = BiometricData.getInstance(extValue.getObjectAt(i));
BiometricData expData = BiometricData.getInstance(extValueInReq.getObjectAt(i));
TypeOfBiometricData isType = isData.getTypeOfBiometricData();
TypeOfBiometricData expType = expData.getTypeOfBiometricData();
if (!isType.equals(expType)) {
String isStr = isType.isPredefined() ? Integer.toString(isType.getPredefinedBiometricType()) : isType.getBiometricDataOid().getId();
String expStr = expType.isPredefined() ? Integer.toString(expType.getPredefinedBiometricType()) : expType.getBiometricDataOid().getId();
addViolation(failureMsg, "biometricData[" + i + "].typeOfBiometricData", isStr, expStr);
}
ASN1ObjectIdentifier is = isData.getHashAlgorithm().getAlgorithm();
ASN1ObjectIdentifier exp = expData.getHashAlgorithm().getAlgorithm();
if (!is.equals(exp)) {
addViolation(failureMsg, "biometricData[" + i + "].hashAlgorithm", is.getId(), exp.getId());
}
ASN1Encodable isHashAlgoParam = isData.getHashAlgorithm().getParameters();
if (isHashAlgoParam == null) {
failureMsg.append("biometricData[").append(i).append("].hashAlgorithm.parameters is 'present' but expected 'absent'; ");
} else {
try {
byte[] isBytes = isHashAlgoParam.toASN1Primitive().getEncoded();
if (!Arrays.equals(isBytes, DER_NULL)) {
addViolation(failureMsg, "biometricData[" + i + "].biometricDataHash.parameters", hex(isBytes), hex(DER_NULL));
}
} catch (IOException ex) {
failureMsg.append("biometricData[").append(i).append("].biometricDataHash.parameters has incorrect syntax; ");
}
}
byte[] isBytes = isData.getBiometricDataHash().getOctets();
byte[] expBytes = expData.getBiometricDataHash().getOctets();
if (!Arrays.equals(isBytes, expBytes)) {
addViolation(failureMsg, "biometricData[" + i + "].biometricDataHash", hex(isBytes), hex(expBytes));
}
DERIA5String str = isData.getSourceDataUri();
String isSourceDataUri = (str == null) ? null : str.getString();
String expSourceDataUri = null;
if (conf.getSourceDataUriOccurrence() != TripleState.FORBIDDEN) {
str = expData.getSourceDataUri();
expSourceDataUri = (str == null) ? null : str.getString();
}
if (expSourceDataUri == null) {
if (isSourceDataUri != null) {
addViolation(failureMsg, "biometricData[" + i + "].sourceDataUri", "present", "absent");
}
} else {
if (isSourceDataUri == null) {
failureMsg.append("biometricData[").append(i).append("].sourceDataUri is 'absent'");
failureMsg.append(" but expected 'present'; ");
} else if (!isSourceDataUri.equals(expSourceDataUri)) {
addViolation(failureMsg, "biometricData[" + i + "].sourceDataUri", isSourceDataUri, expSourceDataUri);
}
}
}
}
Aggregations