use of org.openecard.bouncycastle.asn1.x509.Certificate in project xipki by xipki.
the class OcspBenchRequestor method init.
public void init(OcspBenchmark responseHandler, String responderUrl, Certificate issuerCert, RequestOptions requestOptions, int queueSize) throws Exception {
ParamUtil.requireNonNull("issuerCert", issuerCert);
ParamUtil.requireNonNull("responseHandler", responseHandler);
this.requestOptions = ParamUtil.requireNonNull("requestOptions", requestOptions);
HashAlgo hashAlgo = HashAlgo.getInstance(requestOptions.getHashAlgorithmId());
if (hashAlgo == null) {
throw new OcspRequestorException("unknown HashAlgo " + requestOptions.getHashAlgorithmId().getId());
}
this.issuerhashAlg = hashAlgo.getAlgorithmIdentifier();
this.issuerNameHash = new DEROctetString(hashAlgo.hash(issuerCert.getSubject().getEncoded()));
this.issuerKeyHash = new DEROctetString(hashAlgo.hash(issuerCert.getSubjectPublicKeyInfo().getPublicKeyData().getOctets()));
List<AlgorithmIdentifier> prefSigAlgs = requestOptions.getPreferredSignatureAlgorithms();
if (prefSigAlgs == null || prefSigAlgs.size() == 0) {
this.extensions = null;
} else {
ASN1EncodableVector vec = new ASN1EncodableVector();
for (AlgorithmIdentifier algId : prefSigAlgs) {
ASN1Sequence prefSigAlgObj = new DERSequence(algId);
vec.add(prefSigAlgObj);
}
ASN1Sequence extnValue = new DERSequence(vec);
Extension extn;
try {
extn = new Extension(ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
} catch (IOException ex) {
throw new OcspRequestorException(ex.getMessage(), ex);
}
this.extensions = new Extension[] { extn };
}
URI uri = new URI(responderUrl);
this.responderRawPathPost = uri.getRawPath();
if (this.responderRawPathPost.endsWith("/")) {
this.responderRawPathGet = this.responderRawPathPost;
} else {
this.responderRawPathGet = this.responderRawPathPost + "/";
}
this.httpClient = new HttpClient(responderUrl, responseHandler, queueSize);
this.httpClient.start();
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project xipki by xipki.
the class IssuerEntry method getIssuerHashAndKeys.
private static Map<HashAlgo, byte[]> getIssuerHashAndKeys(byte[] encodedCert) throws CertificateEncodingException {
byte[] encodedName;
byte[] encodedKey;
try {
Certificate bcCert = Certificate.getInstance(encodedCert);
encodedName = bcCert.getSubject().getEncoded("DER");
encodedKey = bcCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
} catch (IllegalArgumentException | IOException ex) {
throw new CertificateEncodingException(ex.getMessage(), ex);
}
Map<HashAlgo, byte[]> hashes = new HashMap<>();
for (HashAlgo ha : HashAlgo.values()) {
int hlen = ha.getLength();
byte[] nameAndKeyHash = new byte[(2 + hlen) << 1];
int offset = 0;
nameAndKeyHash[offset++] = 0x04;
nameAndKeyHash[offset++] = (byte) hlen;
System.arraycopy(ha.hash(encodedName), 0, nameAndKeyHash, offset, hlen);
offset += hlen;
nameAndKeyHash[offset++] = 0x04;
nameAndKeyHash[offset++] = (byte) hlen;
System.arraycopy(ha.hash(encodedKey), 0, nameAndKeyHash, offset, hlen);
offset += hlen;
hashes.put(ha, nameAndKeyHash);
}
return hashes;
}
use of org.openecard.bouncycastle.asn1.x509.Certificate 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.openecard.bouncycastle.asn1.x509.Certificate 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.Certificate in project xipki by xipki.
the class CmpResponder method processPkiMessage.
public PKIMessage processPkiMessage(PKIMessage pkiMessage, X509Certificate tlsClientCert, AuditEvent event) {
ParamUtil.requireNonNull("pkiMessage", pkiMessage);
ParamUtil.requireNonNull("event", event);
GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);
PKIHeader reqHeader = message.getHeader();
ASN1OctetString tid = reqHeader.getTransactionID();
String msgId = null;
if (event != null) {
msgId = RandomUtil.nextHexLong();
event.addEventData(CaAuditConstants.NAME_mid, msgId);
}
if (tid == null) {
byte[] randomBytes = randomTransactionId();
tid = new DEROctetString(randomBytes);
}
String tidStr = Base64.encodeToString(tid.getOctets());
if (event != null) {
event.addEventData(CaAuditConstants.NAME_tid, tidStr);
}
int reqPvno = reqHeader.getPvno().getValue().intValue();
if (reqPvno != PVNO_CMP2000) {
if (event != null) {
event.setLevel(AuditLevel.INFO);
event.setStatus(AuditStatus.FAILED);
event.addEventData(CaAuditConstants.NAME_message, "unsupproted version " + reqPvno);
}
return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.unsupportedVersion, null);
}
CmpControl cmpControl = getCmpControl();
Integer failureCode = null;
String statusText = null;
Date messageTime = null;
if (reqHeader.getMessageTime() != null) {
try {
messageTime = reqHeader.getMessageTime().getDate();
} catch (ParseException ex) {
LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not parse messageTime");
}
}
GeneralName recipient = reqHeader.getRecipient();
boolean intentMe = (recipient == null) ? true : intendsMe(recipient);
if (!intentMe) {
LOG.warn("tid={}: I am not the intended recipient, but '{}'", tid, reqHeader.getRecipient());
failureCode = PKIFailureInfo.badRequest;
statusText = "I am not the intended recipient";
} else if (messageTime == null) {
if (cmpControl.isMessageTimeRequired()) {
failureCode = PKIFailureInfo.missingTimeStamp;
statusText = "missing time-stamp";
}
} else {
long messageTimeBias = cmpControl.getMessageTimeBias();
if (messageTimeBias < 0) {
messageTimeBias *= -1;
}
long msgTimeMs = messageTime.getTime();
long currentTimeMs = System.currentTimeMillis();
long bias = (msgTimeMs - currentTimeMs) / 1000L;
if (bias > messageTimeBias) {
failureCode = PKIFailureInfo.badTime;
statusText = "message time is in the future";
} else if (bias * -1 > messageTimeBias) {
failureCode = PKIFailureInfo.badTime;
statusText = "message too old";
}
}
if (failureCode != null) {
if (event != null) {
event.setLevel(AuditLevel.INFO);
event.setStatus(AuditStatus.FAILED);
event.addEventData(CaAuditConstants.NAME_message, statusText);
}
return buildErrorPkiMessage(tid, reqHeader, failureCode, statusText);
}
boolean isProtected = message.hasProtection();
CmpRequestorInfo requestor;
String errorStatus;
if (isProtected) {
try {
ProtectionVerificationResult verificationResult = verifyProtection(tidStr, message, cmpControl);
ProtectionResult pr = verificationResult.getProtectionResult();
switch(pr) {
case VALID:
errorStatus = null;
break;
case INVALID:
errorStatus = "request is protected by signature but invalid";
break;
case NOT_SIGNATURE_BASED:
errorStatus = "request is not protected by signature";
break;
case SENDER_NOT_AUTHORIZED:
errorStatus = "request is protected by signature but the requestor is not authorized";
break;
case SIGALGO_FORBIDDEN:
errorStatus = "request is protected by signature but the protection algorithm" + " is forbidden";
break;
default:
throw new RuntimeException("should not reach here, unknown ProtectionResult " + pr);
}
// end switch
requestor = (CmpRequestorInfo) verificationResult.getRequestor();
} catch (Exception ex) {
LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not verify the signature");
errorStatus = "request has invalid signature based protection";
requestor = null;
}
} else if (tlsClientCert != null) {
boolean authorized = false;
requestor = getRequestor(reqHeader);
if (requestor != null) {
if (tlsClientCert.equals(requestor.getCert().getCert())) {
authorized = true;
}
}
if (authorized) {
errorStatus = null;
} else {
LOG.warn("tid={}: not authorized requestor (TLS client '{}')", tid, X509Util.getRfc4519Name(tlsClientCert.getSubjectX500Principal()));
errorStatus = "requestor (TLS client certificate) is not authorized";
}
} else {
errorStatus = "request has no protection";
requestor = null;
}
if (errorStatus != null) {
if (event != null) {
event.setLevel(AuditLevel.INFO);
event.setStatus(AuditStatus.FAILED);
event.addEventData(CaAuditConstants.NAME_message, errorStatus);
}
return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.badMessageCheck, errorStatus);
}
PKIMessage resp = processPkiMessage0(pkiMessage, requestor, tid, message, msgId, event);
if (isProtected) {
resp = addProtection(resp, event);
} else {
// protected by TLS connection
}
return resp;
}
Aggregations