use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.
the class CsrValidateCmd method execute0.
@Override
protected Object execute0() throws Exception {
CertificationRequest csr = CertificationRequest.getInstance(IoUtil.read(csrFile));
String sigAlgo = AlgorithmUtil.getSignatureAlgoName(csr.getSignatureAlgorithm());
boolean bo = securityFactory.verifyPopo(csr, null);
String txt = bo ? "valid" : "invalid";
println("The POP is " + txt + " (signature algorithm " + sigAlgo + ").");
return null;
}
use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.
the class ScepImpl method servicePkiOperation0.
// method servicePkiOperation
private PkiMessage servicePkiOperation0(CMSSignedData requestContent, DecodedPkiMessage req, String certProfileName, String msgId, AuditEvent event) throws MessageDecodingException, OperationException {
ParamUtil.requireNonNull("requestContent", requestContent);
ParamUtil.requireNonNull("req", req);
String tid = req.getTransactionId().getId();
// verify and decrypt the request
audit(event, CaAuditConstants.NAME_tid, tid);
if (req.getFailureMessage() != null) {
audit(event, CaAuditConstants.NAME_SCEP_failureMessage, req.getFailureMessage());
}
Boolean bo = req.isSignatureValid();
if (bo != null && !bo.booleanValue()) {
audit(event, CaAuditConstants.NAME_SCEP_signature, "invalid");
}
bo = req.isDecryptionSuccessful();
if (bo != null && !bo.booleanValue()) {
audit(event, CaAuditConstants.NAME_SCEP_decryption, "failed");
}
PkiMessage rep = new PkiMessage(req.getTransactionId(), MessageType.CertRep, Nonce.randomNonce());
rep.setRecipientNonce(req.getSenderNonce());
if (req.getFailureMessage() != null) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badRequest);
return rep;
}
bo = req.isSignatureValid();
if (bo != null && !bo.booleanValue()) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badMessageCheck);
return rep;
}
bo = req.isDecryptionSuccessful();
if (bo != null && !bo.booleanValue()) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badRequest);
return rep;
}
Date signingTime = req.getSigningTime();
if (maxSigningTimeBiasInMs > 0) {
boolean isTimeBad = false;
if (signingTime == null) {
isTimeBad = true;
} else {
long now = System.currentTimeMillis();
long diff = now - signingTime.getTime();
if (diff < 0) {
diff = -1 * diff;
}
isTimeBad = diff > maxSigningTimeBiasInMs;
}
if (isTimeBad) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badTime);
return rep;
}
}
// end if
// check the digest algorithm
String oid = req.getDigestAlgorithm().getId();
ScepHashAlgo hashAlgo = ScepHashAlgo.forNameOrOid(oid);
if (hashAlgo == null) {
LOG.warn("tid={}: unknown digest algorithm {}", tid, oid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
boolean supported = false;
if (hashAlgo == ScepHashAlgo.SHA1) {
if (caCaps.containsCapability(CaCapability.SHA1)) {
supported = true;
}
} else if (hashAlgo == ScepHashAlgo.SHA256) {
if (caCaps.containsCapability(CaCapability.SHA256)) {
supported = true;
}
} else if (hashAlgo == ScepHashAlgo.SHA512) {
if (caCaps.containsCapability(CaCapability.SHA512)) {
supported = true;
}
}
if (!supported) {
LOG.warn("tid={}: unsupported digest algorithm {}", tid, oid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
// check the content encryption algorithm
ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
if (!caCaps.containsCapability(CaCapability.DES3)) {
LOG.warn("tid={}: encryption with DES3 algorithm is not permitted", tid, encOid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
} else if (AES_ENC_ALGOS.contains(encOid)) {
if (!caCaps.containsCapability(CaCapability.AES)) {
LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
} else {
LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
X509Ca ca;
try {
ca = caManager.getX509Ca(caIdent);
} catch (CaMgmtException ex) {
LogUtil.error(LOG, ex, tid + "=" + tid + ",could not get X509CA");
throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
}
X500Name caX500Name = ca.getCaInfo().getCert().getSubjectAsX500Name();
try {
SignedData signedData;
MessageType mt = req.getMessageType();
audit(event, CaAuditConstants.NAME_SCEP_messageType, mt.toString());
switch(mt) {
case PKCSReq:
case RenewalReq:
case UpdateReq:
CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
X500Name reqSubject = csr.getCertificationRequestInfo().getSubject();
if (LOG.isInfoEnabled()) {
LOG.info("tid={}, subject={}", tid, X509Util.getRfc4519Name(reqSubject));
}
try {
ca.checkCsr(csr);
} catch (OperationException ex) {
LogUtil.warn(LOG, ex, "tid=" + tid + " POPO verification failed");
throw FailInfoException.BAD_MESSAGE_CHECK;
}
CertificationRequestInfo csrReqInfo = csr.getCertificationRequestInfo();
X509Certificate reqSignatureCert = req.getSignatureCert();
X500Principal reqSigCertSubject = reqSignatureCert.getSubjectX500Principal();
boolean selfSigned = reqSigCertSubject.equals(reqSignatureCert.getIssuerX500Principal());
if (selfSigned) {
X500Name tmp = X500Name.getInstance(reqSigCertSubject.getEncoded());
if (!tmp.equals(csrReqInfo.getSubject())) {
LOG.warn("tid={}, self-signed identityCert.subject != csr.subject");
throw FailInfoException.BAD_REQUEST;
}
}
if (X509Util.getCommonName(csrReqInfo.getSubject()) == null) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "tid=" + tid + ": no CommonName in requested subject");
}
NameId userIdent = null;
String challengePwd = CaUtil.getChallengePassword(csrReqInfo);
if (challengePwd != null) {
String[] strs = challengePwd.split(":");
if (strs == null || strs.length != 2) {
LOG.warn("tid={}: challengePassword does not have the format <user>:<password>", tid);
throw FailInfoException.BAD_REQUEST;
}
String user = strs[0];
String password = strs[1];
userIdent = ca.authenticateUser(user, password.getBytes());
if (userIdent == null) {
LOG.warn("tid={}: could not authenticate user {}", tid, user);
throw FailInfoException.BAD_REQUEST;
}
}
if (selfSigned) {
if (MessageType.PKCSReq != mt) {
LOG.warn("tid={}: self-signed certificate is not permitted for" + " messageType {}", tid, mt);
throw FailInfoException.BAD_REQUEST;
}
if (userIdent == null) {
LOG.warn("tid={}: could not extract user & password from challengePassword" + ", which are required for self-signed signature certificate", tid);
throw FailInfoException.BAD_REQUEST;
}
} else {
// certificate is known by the CA
if (userIdent == null) {
// up to draft-nourse-scep-23 the client sends all messages to enroll
// certificate via MessageType PKCSReq
KnowCertResult knowCertRes = ca.knowsCertificate(reqSignatureCert);
if (!knowCertRes.isKnown()) {
LOG.warn("tid={}: signature certificate is not trusted by the CA", tid);
throw FailInfoException.BAD_REQUEST;
}
Integer userId = knowCertRes.getUserId();
if (userId == null) {
LOG.warn("tid={}: could not extract user from the signature cert", tid);
throw FailInfoException.BAD_REQUEST;
}
userIdent = ca.getUserIdent(userId);
}
// end if
}
// end if
ByUserRequestorInfo requestor = ca.getByUserRequestor(userIdent);
checkUserPermission(requestor, certProfileName);
byte[] tidBytes = getTransactionIdBytes(tid);
Extensions extensions = CaUtil.getExtensions(csrReqInfo);
CertTemplateData certTemplateData = new CertTemplateData(csrReqInfo.getSubject(), csrReqInfo.getSubjectPublicKeyInfo(), (Date) null, (Date) null, extensions, certProfileName);
X509CertificateInfo cert = ca.generateCertificate(certTemplateData, requestor, RequestType.SCEP, tidBytes, msgId);
/* Don't save SCEP message, since it contains password in plaintext
if (ca.getCaInfo().isSaveRequest() && cert.getCert().getCertId() != null) {
byte[] encodedRequest;
try {
encodedRequest = requestContent.getEncoded();
} catch (IOException ex) {
LOG.warn("could not encode request");
encodedRequest = null;
}
if (encodedRequest != null) {
long reqId = ca.addRequest(encodedRequest);
ca.addRequestCert(reqId, cert.getCert().getCertId());
}
}*/
signedData = buildSignedData(cert.getCert().getCert());
break;
case CertPoll:
IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(is.getIssuer()));
audit(event, CaAuditConstants.NAME_subject, X509Util.getRfc4519Name(is.getSubject()));
ensureIssuedByThisCa(caX500Name, is.getIssuer());
signedData = pollCert(ca, is.getSubject(), req.getTransactionId());
break;
case GetCert:
IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
BigInteger serial = isn.getSerialNumber().getPositiveValue();
audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
audit(event, CaAuditConstants.NAME_serial, LogUtil.formatCsn(serial));
ensureIssuedByThisCa(caX500Name, isn.getName());
signedData = getCert(ca, isn.getSerialNumber().getPositiveValue());
break;
case GetCRL:
isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
serial = isn.getSerialNumber().getPositiveValue();
audit(event, CaAuditConstants.NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
audit(event, CaAuditConstants.NAME_serial, LogUtil.formatCsn(serial));
ensureIssuedByThisCa(caX500Name, isn.getName());
signedData = getCrl(ca, serial);
break;
default:
LOG.error("unknown SCEP messageType '{}'", req.getMessageType());
throw FailInfoException.BAD_REQUEST;
}
// end switch<
ContentInfo ci = new ContentInfo(CMSObjectIdentifiers.signedData, signedData);
rep.setMessageData(ci);
rep.setPkiStatus(PkiStatus.SUCCESS);
} catch (FailInfoException ex) {
LogUtil.error(LOG, ex);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(ex.getFailInfo());
}
return rep;
}
use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.
the class ScepResponder method servicePkiOperation0.
// method servicePkiOperation
private PkiMessage servicePkiOperation0(CMSSignedData requestContent, DecodedPkiMessage req, String certprofileName, String msgId, AuditEvent event) throws OperationException {
notNull(requestContent, "requestContent");
String tid = notNull(req, "req").getTransactionId().getId();
// verify and decrypt the request
audit(event, NAME_tid, tid);
if (req.getFailureMessage() != null) {
audit(event, Scep.NAME_failure_message, req.getFailureMessage());
}
Boolean bo = req.isSignatureValid();
if (bo != null && !bo) {
audit(event, Scep.NAME_signature, "invalid");
}
bo = req.isDecryptionSuccessful();
if (bo != null && !bo) {
audit(event, Scep.NAME_decryption, "failed");
}
PkiMessage rep = new PkiMessage(req.getTransactionId(), MessageType.CertRep, Nonce.randomNonce());
rep.setRecipientNonce(req.getSenderNonce());
if (req.getFailureMessage() != null) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badRequest);
return rep;
}
bo = req.isSignatureValid();
if (bo != null && !bo) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badMessageCheck);
return rep;
}
bo = req.isDecryptionSuccessful();
if (bo != null && !bo) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badRequest);
return rep;
}
Date signingTime = req.getSigningTime();
if (maxSigningTimeBiasInMs > 0) {
boolean isTimeBad;
if (signingTime == null) {
isTimeBad = true;
} else {
long now = System.currentTimeMillis();
long diff = now - signingTime.getTime();
if (diff < 0) {
diff = -1 * diff;
}
isTimeBad = diff > maxSigningTimeBiasInMs;
}
if (isTimeBad) {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badTime);
return rep;
}
}
// end if
// check the digest algorithm
HashAlgo hashAlgo = req.getDigestAlgorithm();
boolean supported = false;
if (hashAlgo == HashAlgo.SHA1) {
if (caCaps.supportsSHA1()) {
supported = true;
}
} else if (hashAlgo == HashAlgo.SHA256) {
if (caCaps.supportsSHA256()) {
supported = true;
}
} else if (hashAlgo == HashAlgo.SHA512) {
if (caCaps.supportsSHA512()) {
supported = true;
}
}
if (!supported) {
LOG.warn("tid={}: unsupported digest algorithm {}", tid, hashAlgo);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
// check the content encryption algorithm
ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
if (!caCaps.supportsDES3()) {
LOG.warn("tid={}: encryption with DES3 algorithm {} is not permitted", tid, encOid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
} else if (CMSAlgorithm.AES128_CBC.equals(encOid)) {
if (!caCaps.supportsAES()) {
LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
} else {
LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badAlg);
return rep;
}
X509Ca ca;
try {
ca = caManager.getX509Ca(caIdent);
} catch (CaMgmtException ex) {
LogUtil.error(LOG, ex, tid + "=" + tid + ",could not get X509CA");
throw new OperationException(SYSTEM_FAILURE, ex);
}
X500Name caX500Name = ca.getCaInfo().getCert().getSubject();
try {
SignedData signedData;
MessageType mt = req.getMessageType();
audit(event, Scep.NAME_message_type, mt.toString());
switch(mt) {
case PKCSReq:
case RenewalReq:
CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
X500Name reqSubject = csr.getCertificationRequestInfo().getSubject();
if (LOG.isInfoEnabled()) {
LOG.info("tid={}, subject={}", tid, X509Util.getRfc4519Name(reqSubject));
}
if (!ca.verifyCsr(csr)) {
LOG.warn("tid={} POP verification failed", tid);
throw FailInfoException.BAD_MESSAGE_CHECK;
}
CertificationRequestInfo csrReqInfo = csr.getCertificationRequestInfo();
X509Cert reqSignatureCert = req.getSignatureCert();
X500Name reqSigCertSubject = reqSignatureCert.getSubject();
boolean selfSigned = reqSignatureCert.isSelfSigned();
if (selfSigned) {
if (!reqSigCertSubject.equals(csrReqInfo.getSubject())) {
LOG.warn("tid={}, self-signed identityCert.subject ({}) != csr.subject ({})", tid, reqSigCertSubject, csrReqInfo.getSubject());
throw FailInfoException.BAD_REQUEST;
}
}
if (X509Util.getCommonName(csrReqInfo.getSubject()) == null) {
throw new OperationException(BAD_CERT_TEMPLATE, "tid=" + tid + ": no CommonName in requested subject");
}
NameId userIdent = null;
String challengePwd = CaUtil.getChallengePassword(csrReqInfo);
if (challengePwd != null) {
String[] strs = challengePwd.split(":");
if (strs.length != 2) {
LOG.warn("tid={}: challengePassword does not have the format <user>:<password>", tid);
throw FailInfoException.BAD_REQUEST;
}
String user = strs[0];
String password = strs[1];
userIdent = ca.authenticateUser(user, StringUtil.toUtf8Bytes(password));
if (userIdent == null) {
LOG.warn("tid={}: could not authenticate user {}", tid, user);
throw FailInfoException.BAD_REQUEST;
}
}
if (selfSigned) {
if (MessageType.PKCSReq != mt) {
LOG.warn("tid={}: self-signed certificate is not permitted for" + " messageType {}", tid, mt);
throw FailInfoException.BAD_REQUEST;
}
if (userIdent == null) {
LOG.warn("tid={}: could not extract user & password from challengePassword" + ", which are required for self-signed signature certificate", tid);
throw FailInfoException.BAD_REQUEST;
}
} else {
// certificate is known by the CA
if (userIdent == null) {
// up to draft-nourse-scep-23 the client sends all messages to enroll
// certificate via MessageType PKCSReq
KnowCertResult knowCertRes = ca.knowsCert(reqSignatureCert);
if (!knowCertRes.isKnown()) {
LOG.warn("tid={}: signature certificate is not trusted by the CA", tid);
throw FailInfoException.BAD_REQUEST;
}
Integer userId = knowCertRes.getUserId();
if (userId == null) {
LOG.warn("tid={}: could not extract user from the signature cert", tid);
throw FailInfoException.BAD_REQUEST;
}
userIdent = ca.getUserIdent(userId);
}
// end if
}
// end if
RequestorInfo.ByUserRequestorInfo requestor = ca.getByUserRequestor(userIdent);
checkUserPermission(requestor, certprofileName);
byte[] tidBytes = getTransactionIdBytes(tid);
Extensions extensions = CaUtil.getExtensions(csrReqInfo);
CertTemplateData certTemplateData = new CertTemplateData(csrReqInfo.getSubject(), csrReqInfo.getSubjectPublicKeyInfo(), null, null, extensions, certprofileName);
CertificateInfo cert = ca.generateCert(certTemplateData, requestor, RequestType.SCEP, tidBytes, msgId);
/* Don't save SCEP message, since it contains password in plaintext
if (ca.getCaInfo().isSaveRequest() && cert.getCert().getCertId() != null) {
byte[] encodedRequest;
try {
encodedRequest = requestContent.getEncoded();
} catch (IOException ex) {
LOG.warn("could not encode request");
encodedRequest = null;
}
if (encodedRequest != null) {
long reqId = ca.addRequest(encodedRequest);
ca.addRequestCert(reqId, cert.getCert().getCertId());
}
}*/
signedData = buildSignedData(cert.getCert().getCert());
break;
case CertPoll:
IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
audit(event, NAME_issuer, X509Util.getRfc4519Name(is.getIssuer()));
audit(event, NAME_subject, X509Util.getRfc4519Name(is.getSubject()));
ensureIssuedByThisCa(caX500Name, is.getIssuer());
signedData = pollCert(ca, is.getSubject(), req.getTransactionId());
break;
case GetCert:
IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
BigInteger serial = isn.getSerialNumber().getPositiveValue();
audit(event, NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
audit(event, NAME_serial, LogUtil.formatCsn(serial));
ensureIssuedByThisCa(caX500Name, isn.getName());
signedData = getCert(ca, isn.getSerialNumber().getPositiveValue());
break;
case GetCRL:
isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
serial = isn.getSerialNumber().getPositiveValue();
audit(event, NAME_issuer, X509Util.getRfc4519Name(isn.getName()));
audit(event, NAME_serial, LogUtil.formatCsn(serial));
ensureIssuedByThisCa(caX500Name, isn.getName());
signedData = getCrl(ca, serial);
break;
default:
LOG.error("unknown SCEP messageType '{}'", req.getMessageType());
throw FailInfoException.BAD_REQUEST;
}
// end switch
ContentInfo ci = new ContentInfo(CMSObjectIdentifiers.signedData, signedData);
rep.setMessageData(ci);
rep.setPkiStatus(PkiStatus.SUCCESS);
} catch (FailInfoException ex) {
LogUtil.error(LOG, ex);
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(ex.getFailInfo());
}
return rep;
}
use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.
the class SignatureCmpCaClientExample method main.
public static void main(String[] args) {
if (!new File(KEYCERT_DIR).exists()) {
System.err.println("Please call \"mvn generate-resources\" first.");
return;
}
Security.addProvider(new BouncyCastleProvider());
try {
KeyStore ks = KeyStore.getInstance("PKCS12");
char[] password = REQUESTOR_KEYSTORE_PASSWORD.toCharArray();
InputStream ksStream = Files.newInputStream(Paths.get(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 responderCert = SdkUtil.parseCert(new File(expandPath(RESPONDER_CERT_FILE)));
CmpCaClient client = new SignatureCmpCaClient(CMP_URL, null, requestorKey, requestorCert, responderCert, HASH_ALGO);
client.init();
X509Certificate caCert = client.getCaCert();
X500Name issuer = X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded());
// retrieve CA certificate
printCert("===== CA Certificate =====", client.getCaCert());
// Enroll certificate via CRMF - (CA generate keypair)
KeyAndCert[] keyAndCerts = client.enrollCertsViaCrmfCaGenKeypair(new String[] { CERT_PROFILE, CERT_PROFILE }, new String[] { getSubject(), getSubject() });
for (int i = 0; i < keyAndCerts.length; i++) {
printKeyAndCert("===== Enroll via CRMF (CMP, CA generate keypair) =====", keyAndCerts[i]);
}
// Enroll certificate via CSR - RSA
MyKeypair kp = generateRsaKeypair();
CertificationRequest csr = genCsr(kp, getSubject());
X509Certificate cert = client.enrollCertViaCsr(CERT_PROFILE, csr);
printCert("===== Enroll RSA via CSR (CMP) =====", cert);
// Enroll certificate via CSR - EC
kp = generateEcKeypair();
csr = genCsr(kp, getSubject());
cert = client.enrollCertViaCsr(CERT_PROFILE, csr);
printCert("===== Enroll Enroll EC via CSR (CMP) =====", cert);
// Enroll certificate via CSR - DSA
kp = generateDsaKeypair();
csr = genCsr(kp, getSubject());
cert = client.enrollCertViaCsr(CERT_PROFILE, csr);
printCert("===== Enroll DSA via CSR (CMP) =====", cert);
// Enroll certificate via CRMF - RSA
kp = generateRsaKeypair();
cert = client.enrollCertViaCrmf(CERT_PROFILE, kp.getPrivate(), kp.getPublic(), getSubject());
printCert("===== Enroll Enroll RSA via CRMF (CMP) =====", cert);
// Update certificate via CRMF - RSA
cert = client.updateCertViaCrmf(kp.getPrivate(), issuer, cert.getSerialNumber());
printCert("===== Update RSA via CRMF (CMP) =====", cert);
// Update certificate via CRMF - RSA (CA generate key pair)
KeyAndCert keyAndCert = client.updateCertViaCrmfCaGenKeypair(issuer, cert.getSerialNumber());
printKeyAndCert("===== Update via CRMF (CMP, CA generate keypair) =====", keyAndCert);
// Enroll certificate via CRMF - EC
kp = generateEcKeypair();
MyKeypair kp2 = generateEcKeypair();
X509Certificate[] certs = client.enrollCertsViaCrmf(new String[] { CERT_PROFILE, CERT_PROFILE }, new PrivateKey[] { kp.getPrivate(), kp2.getPrivate() }, new SubjectPublicKeyInfo[] { kp.getPublic(), kp2.getPublic() }, new String[] { getSubject(), getSubject() });
for (int i = 0; i < certs.length; i++) {
printCert("===== Enroll EC via CRMF (CMP) =====", certs[i]);
}
// Update certificate via CRMF - EC
certs = client.updateCertsViaCrmf(new PrivateKey[] { kp.getPrivate(), kp2.getPrivate() }, issuer, new BigInteger[] { certs[0].getSerialNumber(), certs[1].getSerialNumber() });
for (int i = 0; i < certs.length; i++) {
printCert("===== Update EC via CRMF (CMP) =====", certs[i]);
}
// Enroll certificate via CRMF - DSA
kp = generateDsaKeypair();
cert = client.enrollCertViaCrmf(CERT_PROFILE, kp.getPrivate(), kp.getPublic(), getSubject());
printCert("===== Enroll DSA via CRMF (CMP) =====", cert);
// Update certificate via CRMF - DSA
cert = client.updateCertViaCrmf(kp.getPrivate(), issuer, cert.getSerialNumber());
printCert("===== Update 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.close();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(-1);
}
}
use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.
the class AbstractCaTest method doTest.
private void doTest(KeyPair keypair) throws Exception {
CaIdentifier caId = new CaIdentifier("http://localhost:" + port + "/scep/pkiclient.exe", null);
CaCertValidator caCertValidator = new CaCertValidator.PreprovisionedCaCertValidator(scepServer.getCaCert());
ScepClient client = new ScepClient(caId, caCertValidator);
client.refresh();
CaCaps expCaCaps = getExpectedCaCaps();
// CACaps
CaCaps caCaps = client.getCaCaps();
Assert.assertEquals("CACaps", expCaCaps, caCaps);
// CA certificate
X509Cert expCaCert = scepServer.getCaCert();
X509Cert caCert = client.getAuthorityCertStore().getCaCert();
if (!expCaCert.equals(caCert)) {
Assert.fail("Configured and received CA certificate not the same");
}
boolean withRa = isWithRa();
// RA
if (withRa) {
X509Cert expRaCert = scepServer.getRaCert();
X509Cert raSigCert = client.getAuthorityCertStore().getSignatureCert();
X509Cert raEncCert = client.getAuthorityCertStore().getEncryptionCert();
Assert.assertEquals("RA certificate", raSigCert, raEncCert);
if (!expRaCert.equals(raSigCert)) {
Assert.fail("Configured and received RA certificate not the same");
}
}
// getNextCA
if (isWithNextCa()) {
AuthorityCertStore nextCa = client.scepNextCaCert();
X509Cert expNextCaCert = scepServer.getNextCaCert();
X509Cert nextCaCert = nextCa.getCaCert();
if (!expNextCaCert.equals(nextCaCert)) {
Assert.fail("Configured and received next CA certificate not the same");
}
if (withRa) {
X509Cert expNextRaCert = scepServer.getNextRaCert();
X509Cert nextRaSigCert = nextCa.getSignatureCert();
X509Cert nextRaEncCert = nextCa.getEncryptionCert();
Assert.assertEquals("Next RA certificate", nextRaSigCert, nextRaEncCert);
if (!expNextRaCert.equals(nextRaSigCert)) {
Assert.fail("Configured and received next RA certificate not the same");
}
}
}
// enroll
X509Cert selfSignedCert;
X509Cert enroledCert;
X500Name issuerName = caCert.getSubject();
PrivateKey privKey;
CertificationRequest csr;
{
privKey = keypair.getPrivate();
SubjectPublicKeyInfo subjectPublicKeyInfo = MyUtil.createSubjectPublicKeyInfo(keypair.getPublic());
X500Name subject = new X500Name("CN=EE1, OU=emulator, O=myorg.org, C=DE");
// first try without secret
PKCS10CertificationRequest p10Req = MyUtil.generateRequest(privKey, subjectPublicKeyInfo, subject, null, null);
/*
selfSignedCert = MyUtil.generateSelfsignedCert(p10Req.toASN1Structure(), privKey);
EnrolmentResponse enrolResp = client.scepPkcsReq(p10Req.toASN1Structure(), privKey,
selfSignedCert);
PkiStatus status = enrolResp.getPkcsRep().getPkiStatus();
Assert.assertEquals("PkiStatus without secret", PkiStatus.FAILURE, status);
// then try invalid secret
p10Req = MyUtil.generateRequest(privKey, subjectPublicKeyInfo, subject,
"invalid-" + secret, null);
selfSignedCert = MyUtil.generateSelfsignedCert(p10Req.toASN1Structure(), privKey);
enrolResp = client.scepPkcsReq(p10Req.toASN1Structure(), privKey, selfSignedCert);
status = enrolResp.getPkcsRep().getPkiStatus();
Assert.assertEquals("PkiStatus with invalid secret", PkiStatus.FAILURE, status);
*/
// try with valid secret
p10Req = MyUtil.generateRequest(privKey, subjectPublicKeyInfo, subject, secret, null);
selfSignedCert = MyUtil.generateSelfsignedCert(p10Req.toASN1Structure(), privKey);
EnrolmentResponse enrolResp = client.scepPkcsReq(p10Req.toASN1Structure(), privKey, selfSignedCert);
List<X509Cert> certs = enrolResp.getCertificates();
Assert.assertTrue("number of received certificates", certs.size() > 0);
X509Cert cert = certs.get(0);
Assert.assertNotNull("enroled certificate", cert);
enroledCert = cert;
// try :: self-signed certificate's subject different from the one of CSR
p10Req = MyUtil.generateRequest(privKey, subjectPublicKeyInfo, subject, secret, null);
csr = p10Req.toASN1Structure();
selfSignedCert = MyUtil.generateSelfsignedCert(new X500Name("CN=dummy"), csr.getCertificationRequestInfo().getSubjectPublicKeyInfo(), privKey);
enrolResp = client.scepPkcsReq(p10Req.toASN1Structure(), privKey, selfSignedCert);
PkiStatus status = enrolResp.getPkcsRep().getPkiStatus();
Assert.assertEquals("PkiStatus with invalid secret", PkiStatus.FAILURE, status);
}
// certPoll
EnrolmentResponse enrolResp = client.scepCertPoll(privKey, selfSignedCert, csr, issuerName);
List<X509Cert> certs = enrolResp.getCertificates();
Assert.assertTrue("number of received certificates", certs.size() > 0);
X509Cert cert = certs.get(0);
Assert.assertNotNull("enrolled certificate", cert);
// getCert
certs = client.scepGetCert(privKey, selfSignedCert, issuerName, enroledCert.getSerialNumber());
Assert.assertTrue("number of received certificates", certs.size() > 0);
cert = certs.get(0);
Assert.assertNotNull("received certificate", cert);
// getCRL
X509CRLHolder crl = client.scepGetCrl(privKey, enroledCert, issuerName, enroledCert.getSerialNumber());
Assert.assertNotNull("received CRL", crl);
// getNextCA
AuthorityCertStore nextCa = client.scepNextCaCert();
Assert.assertNotNull("nextCa", nextCa);
}
Aggregations