use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.
the class CmpCaClientExample method main.
public static void main(String[] args) {
try {
KeyStore ks = KeyStore.getInstance("PKCS12");
char[] password = REQUESTOR_KEYSTORE_PASSWORD.toCharArray();
FileInputStream ksStream = new FileInputStream(expandPath(REQUESTOR_KEYSTORE_FILE));
ks.load(ksStream, password);
ksStream.close();
Enumeration<String> aliases = ks.aliases();
String alias = null;
while (aliases.hasMoreElements()) {
String tmp = aliases.nextElement();
if (ks.isKeyEntry(tmp)) {
alias = tmp;
break;
}
}
PrivateKey requestorKey = (PrivateKey) ks.getKey(alias, password);
X509Certificate requestorCert = (X509Certificate) ks.getCertificate(alias);
X509Certificate caCert = SdkUtil.parseCert(new File(expandPath(CA_CERT_FILE)));
X509Certificate responderCert = SdkUtil.parseCert(new File(expandPath(RESPONDER_CERT_FILE)));
CmpCaClient client = new CmpCaClient(CA_URL, caCert, requestorKey, requestorCert, responderCert, HASH_ALGO);
// Since xipki-2.2.1 the specification of CA certificate is not required, it can
// be retrieved via the CMP protocol
//
// CmpCaClient client = new CmpCaClient(CA_URL, requestorKey, requestorCert,
// responderCert, HASH_ALGO);
client.init();
// retrieve CA certificate
printCert("===== CA Certificate =====", client.getCaCert());
// Enroll certificate via CSR - RSA
MyKeypair kp = generateRsaKeypair();
CertificationRequest csr = genCsr(kp, getSubject());
X509Certificate cert = client.requestCertViaCsr(CERT_PROFILE, csr);
printCert("===== RSA via CSR (CMP) =====", cert);
// Enroll certificate via CSR - EC
kp = generateEcKeypair();
csr = genCsr(kp, getSubject());
cert = client.requestCertViaCsr(CERT_PROFILE, csr);
printCert("===== EC via CSR (CMP) =====", cert);
// Enroll certificate via CSR - DSA
kp = generateDsaKeypair();
csr = genCsr(kp, getSubject());
cert = client.requestCertViaCsr(CERT_PROFILE, csr);
printCert("===== DSA via CSR (CMP) =====", cert);
// Enroll certificate via CRMF - RSA
kp = generateRsaKeypair();
cert = client.requestCertViaCrmf(CERT_PROFILE, kp.getPrivate(), kp.getPublic(), getSubject());
printCert("===== RSA via CRMF (CMP) =====", cert);
// Enroll certificate via CRMF - EC
kp = generateEcKeypair();
cert = client.requestCertViaCrmf(CERT_PROFILE, kp.getPrivate(), kp.getPublic(), getSubject());
printCert("===== EC via CRMF (CMP) =====", cert);
// Enroll certificate via CRMF - DSA
kp = generateDsaKeypair();
cert = client.requestCertViaCrmf(CERT_PROFILE, kp.getPrivate(), kp.getPublic(), getSubject());
printCert("===== DSA via CRMF (CMP) =====", cert);
BigInteger serialNumber = cert.getSerialNumber();
// Suspend certificate
boolean flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.certificateHold));
if (flag) {
System.out.println("(CMP) suspended certificate");
} else {
System.err.println("(CMP) suspending certificate failed");
}
// Unsuspend certificate
flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.removeFromCRL));
if (flag) {
System.out.println("(CMP) unsuspended certificate");
} else {
System.err.println("(CMP) unsuspending certificate failed");
}
// Revoke certificate
flag = client.revokeCert(serialNumber, CRLReason.lookup(CRLReason.keyCompromise));
if (flag) {
System.out.println("(CMP) revoked certificate");
} else {
System.err.println("(CMP) revoking certificate failed");
}
client.shutdown();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(-1);
}
}
use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.
the class CaClientExample method genCsr.
protected static CertificationRequest genCsr(MyKeypair keypair, String subject, String challengePassword) throws GeneralSecurityException, OperatorCreationException {
X500Name subjectDn = new X500Name(subject);
PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(subjectDn, keypair.publicKeyInfo);
if (challengePassword != null && !challengePassword.isEmpty()) {
csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword));
}
ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
return csrBuilder.build(signer).toASN1Structure();
}
use of org.bouncycastle.asn1.pkcs.CertificationRequest in project xipki by xipki.
the class X509SelfSignedCertBuilder method generateSelfSigned.
public static GenerateSelfSignedResult generateSelfSigned(SecurityFactory securityFactory, String signerType, String signerConf, IdentifiedX509Certprofile certprofile, CertificationRequest csr, BigInteger serialNumber, List<String> caCertUris, List<String> ocspUris, List<String> crlUris, List<String> deltaCrlUris, ConfPairs extraControl) throws OperationException, InvalidConfException {
ParamUtil.requireNonNull("securityFactory", securityFactory);
ParamUtil.requireNonBlank("signerType", signerType);
ParamUtil.requireNonNull("certprofile", certprofile);
ParamUtil.requireNonNull("csr", csr);
ParamUtil.requireNonNull("serialNumber", serialNumber);
if (serialNumber.compareTo(BigInteger.ZERO) != 1) {
throw new IllegalArgumentException("serialNumber must not be non-positive: " + serialNumber);
}
X509CertLevel level = certprofile.getCertLevel();
if (X509CertLevel.RootCA != level) {
throw new IllegalArgumentException("certprofile is not of level " + X509CertLevel.RootCA);
}
if (!securityFactory.verifyPopo(csr, null)) {
throw new InvalidConfException("could not validate POP for the CSR");
}
if ("pkcs12".equalsIgnoreCase(signerType) || "jks".equalsIgnoreCase(signerType)) {
ConfPairs keyValues = new ConfPairs(signerConf);
String keystoreConf = keyValues.value("keystore");
if (keystoreConf == null) {
throw new InvalidConfException("required parameter 'keystore' for types PKCS12 and JKS, is not specified");
}
}
ConcurrentContentSigner signer;
try {
List<String[]> signerConfs = CaEntry.splitCaSignerConfs(signerConf);
List<String> restrictedSigAlgos = certprofile.getSignatureAlgorithms();
String thisSignerConf = null;
if (CollectionUtil.isEmpty(restrictedSigAlgos)) {
thisSignerConf = signerConfs.get(0)[1];
} else {
for (String algo : restrictedSigAlgos) {
for (String[] m : signerConfs) {
if (m[0].equals(algo)) {
thisSignerConf = m[1];
break;
}
}
if (thisSignerConf != null) {
break;
}
}
}
if (thisSignerConf == null) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile");
}
signer = securityFactory.createSigner(signerType, new SignerConf(thisSignerConf), (X509Certificate[]) null);
} catch (XiSecurityException | ObjectCreationException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
}
SubjectPublicKeyInfo publicKeyInfo;
if (signer.getCertificate() != null) {
// this cert is the dummy one which can be considered only as public key container
Certificate bcCert;
try {
bcCert = Certificate.getInstance(signer.getCertificate().getEncoded());
} catch (Exception ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not reparse certificate: " + ex.getMessage());
}
publicKeyInfo = bcCert.getSubjectPublicKeyInfo();
} else {
PublicKey signerPublicKey = signer.getPublicKey();
try {
publicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signerPublicKey);
} catch (InvalidKeyException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "cannot generate SubjectPublicKeyInfo from publicKey: " + ex.getMessage());
}
}
X509Certificate newCert = generateCertificate(signer, certprofile, csr, serialNumber, publicKeyInfo, caCertUris, ocspUris, crlUris, deltaCrlUris, extraControl);
return new GenerateSelfSignedResult(signerConf, newCert);
}
use of org.bouncycastle.asn1.pkcs.CertificationRequest 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.bouncycastle.asn1.pkcs.CertificationRequest 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);
}
Aggregations