use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.
the class XiOCSPReqBuilder method generateRequest.
private OCSPRequest generateRequest(ContentSigner contentSigner, Certificate[] chain) throws OCSPException {
Iterator<RequestObject> it = list.iterator();
ASN1EncodableVector requests = new ASN1EncodableVector();
while (it.hasNext()) {
try {
requests.add(((RequestObject) it.next()).toRequest());
} catch (Exception ex) {
throw new OCSPException("exception creating Request", ex);
}
}
TBSRequest tbsReq = new TBSRequest(requestorName, new DERSequence(requests), requestExtensions);
Signature signature = null;
if (contentSigner != null) {
if (requestorName == null) {
throw new OCSPException("requestorName must be specified if request is signed.");
}
try {
// CHECKSTYLE:SKIP
OutputStream sOut = contentSigner.getOutputStream();
sOut.write(tbsReq.getEncoded(ASN1Encoding.DER));
sOut.close();
} catch (Exception ex) {
throw new OCSPException("exception processing TBSRequest: " + ex, ex);
}
DERBitString bitSig = new DERBitString(contentSigner.getSignature());
AlgorithmIdentifier sigAlgId = contentSigner.getAlgorithmIdentifier();
if (chain != null && chain.length > 0) {
ASN1EncodableVector vec = new ASN1EncodableVector();
for (int i = 0; i != chain.length; i++) {
vec.add(chain[i]);
}
signature = new Signature(sigAlgId, bitSig, new DERSequence(vec));
} else {
signature = new Signature(sigAlgId, bitSig);
}
}
return new OCSPRequest(tbsReq, signature);
}
use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.
the class OcspQa method checkOcsp.
public ValidationResult checkOcsp(OCSPResp response, IssuerHash issuerHash, List<BigInteger> serialNumbers, Map<BigInteger, byte[]> encodedCerts, OcspError expectedOcspError, Map<BigInteger, OcspCertStatus> expectedOcspStatuses, Map<BigInteger, Date> expectedRevTimes, OcspResponseOption responseOption, boolean noSigVerify) {
ParamUtil.requireNonNull("response", response);
ParamUtil.requireNonEmpty("serialNumbers", serialNumbers);
ParamUtil.requireNonEmpty("expectedOcspStatuses", expectedOcspStatuses);
ParamUtil.requireNonNull("responseOption", responseOption);
List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>();
int status = response.getStatus();
// Response status
ValidationIssue issue = new ValidationIssue("OCSP.STATUS", "response.status");
resultIssues.add(issue);
if (expectedOcspError != null) {
if (status != expectedOcspError.getStatus()) {
issue.setFailureMessage("is '" + status + "', but expected '" + expectedOcspError.getStatus() + "'");
}
} else {
if (status != 0) {
issue.setFailureMessage("is '" + status + "', but expected '0'");
}
}
if (status != 0) {
return new ValidationResult(resultIssues);
}
ValidationIssue encodingIssue = new ValidationIssue("OCSP.ENCODING", "response encoding");
resultIssues.add(encodingIssue);
BasicOCSPResp basicResp;
try {
basicResp = (BasicOCSPResp) response.getResponseObject();
} catch (OCSPException ex) {
encodingIssue.setFailureMessage(ex.getMessage());
return new ValidationResult(resultIssues);
}
SingleResp[] singleResponses = basicResp.getResponses();
issue = new ValidationIssue("OCSP.RESPONSES.NUM", "number of single responses");
resultIssues.add(issue);
if (singleResponses == null || singleResponses.length == 0) {
issue.setFailureMessage("received no status from server");
return new ValidationResult(resultIssues);
}
final int n = singleResponses.length;
if (n != serialNumbers.size()) {
issue.setFailureMessage("is '" + n + "', but expected '" + serialNumbers.size() + "'");
return new ValidationResult(resultIssues);
}
boolean hasSignature = basicResp.getSignature() != null;
// check the signature if available
if (noSigVerify) {
issue = new ValidationIssue("OCSP.SIG", (hasSignature ? "signature presence (Ignore)" : "signature presence"));
} else {
issue = new ValidationIssue("OCSP.SIG", "signature presence");
}
resultIssues.add(issue);
if (!hasSignature) {
issue.setFailureMessage("response is not signed");
}
if (hasSignature & !noSigVerify) {
// signature algorithm
issue = new ValidationIssue("OCSP.SIG.ALG", "signature algorithm");
resultIssues.add(issue);
String expectedSigalgo = responseOption.getSignatureAlgName();
if (expectedSigalgo != null) {
AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
try {
String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
if (!AlgorithmUtil.equalsAlgoName(sigAlgName, expectedSigalgo)) {
issue.setFailureMessage("is '" + sigAlgName + "', but expected '" + expectedSigalgo + "'");
}
} catch (NoSuchAlgorithmException ex) {
issue.setFailureMessage("could not extract the signature algorithm");
}
}
// end if (expectedSigalgo != null)
// signer certificate
ValidationIssue sigSignerCertIssue = new ValidationIssue("OCSP.SIGNERCERT", "signer certificate");
resultIssues.add(sigSignerCertIssue);
// signature validation
ValidationIssue sigValIssue = new ValidationIssue("OCSP.SIG.VALIDATION", "signature validation");
resultIssues.add(sigValIssue);
X509CertificateHolder respSigner = null;
X509CertificateHolder[] responderCerts = basicResp.getCerts();
if (responderCerts == null || responderCerts.length < 1) {
sigSignerCertIssue.setFailureMessage("no responder certificate is contained in the response");
sigValIssue.setFailureMessage("could not find certificate to validate signature");
} else {
ResponderID respId = basicResp.getResponderId().toASN1Primitive();
X500Name respIdByName = respId.getName();
byte[] respIdByKey = respId.getKeyHash();
for (X509CertificateHolder cert : responderCerts) {
if (respIdByName != null) {
if (cert.getSubject().equals(respIdByName)) {
respSigner = cert;
}
} else {
byte[] spkiSha1 = HashAlgo.SHA1.hash(cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
if (Arrays.equals(respIdByKey, spkiSha1)) {
respSigner = cert;
}
}
if (respSigner != null) {
break;
}
}
if (respSigner == null) {
sigSignerCertIssue.setFailureMessage("no responder certificate match the ResponderId");
sigValIssue.setFailureMessage("could not find certificate matching the" + " ResponderId to validate signature");
}
}
if (respSigner != null) {
issue = new ValidationIssue("OCSP.SIGNERCERT.TRUST", "signer certificate validation");
resultIssues.add(issue);
for (int i = 0; i < singleResponses.length; i++) {
SingleResp singleResp = singleResponses[i];
if (!respSigner.isValidOn(singleResp.getThisUpdate())) {
issue.setFailureMessage(String.format("responder certificate is not valid on the thisUpdate[%d]: %s", i, singleResp.getThisUpdate()));
}
}
// end for
X509Certificate respIssuer = responseOption.getRespIssuer();
if (!issue.isFailed() && respIssuer != null) {
X509Certificate jceRespSigner;
try {
jceRespSigner = X509Util.toX509Cert(respSigner.toASN1Structure());
if (X509Util.issues(respIssuer, jceRespSigner)) {
jceRespSigner.verify(respIssuer.getPublicKey());
} else {
issue.setFailureMessage("responder signer is not trusted");
}
} catch (Exception ex) {
issue.setFailureMessage("responder signer is not trusted");
}
}
try {
PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(responderPubKey);
boolean sigValid = basicResp.isSignatureValid(cvp);
if (!sigValid) {
sigValIssue.setFailureMessage("signature is invalid");
}
} catch (Exception ex) {
sigValIssue.setFailureMessage("could not validate signature");
}
}
// end if
}
// end if (hasSignature)
// nonce
Extension nonceExtn = basicResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
resultIssues.add(checkOccurrence("OCSP.NONCE", nonceExtn, responseOption.getNonceOccurrence()));
boolean extendedRevoke = basicResp.getExtension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke) != null;
for (int i = 0; i < singleResponses.length; i++) {
SingleResp singleResp = singleResponses[i];
BigInteger serialNumber = singleResp.getCertID().getSerialNumber();
OcspCertStatus expectedStatus = expectedOcspStatuses.get(serialNumber);
Date expectedRevTime = null;
if (expectedRevTimes != null) {
expectedRevTime = expectedRevTimes.get(serialNumber);
}
byte[] encodedCert = null;
if (encodedCerts != null) {
encodedCert = encodedCerts.get(serialNumber);
}
List<ValidationIssue> issues = checkSingleCert(i, singleResp, issuerHash, expectedStatus, encodedCert, expectedRevTime, extendedRevoke, responseOption.getNextUpdateOccurrence(), responseOption.getCerthashOccurrence(), responseOption.getCerthashAlgId());
resultIssues.addAll(issues);
}
return new ValidationResult(resultIssues);
}
use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.
the class X509CaCmpResponderImpl method verifyPopo.
// method revokePendingCertificates
private boolean verifyPopo(CertificateRequestMessage certRequest, boolean allowRaPopo) {
int popType = certRequest.getProofOfPossessionType();
if (popType == CertificateRequestMessage.popRaVerified && allowRaPopo) {
return true;
}
if (popType != CertificateRequestMessage.popSigningKey) {
LOG.error("unsupported POP type: " + popType);
return false;
}
// check the POP signature algorithm
ProofOfPossession pop = certRequest.toASN1Structure().getPopo();
POPOSigningKey popoSign = POPOSigningKey.getInstance(pop.getObject());
AlgorithmIdentifier popoAlgId = popoSign.getAlgorithmIdentifier();
AlgorithmValidator algoValidator = getCmpControl().getPopoAlgoValidator();
if (!algoValidator.isAlgorithmPermitted(popoAlgId)) {
String algoName;
try {
algoName = AlgorithmUtil.getSignatureAlgoName(popoAlgId);
} catch (NoSuchAlgorithmException ex) {
algoName = popoAlgId.getAlgorithm().getId();
}
LOG.error("POPO signature algorithm {} not permitted", algoName);
return false;
}
try {
PublicKey publicKey = securityFactory.generatePublicKey(certRequest.getCertTemplate().getPublicKey());
ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(publicKey);
return certRequest.isValidSigningKeyPOP(cvp);
} catch (InvalidKeyException | IllegalStateException | CRMFException ex) {
LogUtil.error(LOG, ex);
}
return false;
}
use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.
the class CsrGenAction method execute0.
@Override
protected Object execute0() throws Exception {
hashAlgo = hashAlgo.trim().toUpperCase();
if (hashAlgo.indexOf('-') != -1) {
hashAlgo = hashAlgo.replaceAll("-", "");
}
if (needExtensionTypes == null) {
needExtensionTypes = new LinkedList<>();
}
if (wantExtensionTypes == null) {
wantExtensionTypes = new LinkedList<>();
}
// SubjectAltNames
List<Extension> extensions = new LinkedList<>();
ASN1OctetString extnValue = createExtnValueSubjectAltName();
if (extnValue != null) {
ASN1ObjectIdentifier oid = Extension.subjectAlternativeName;
extensions.add(new Extension(oid, false, extnValue));
needExtensionTypes.add(oid.getId());
}
// SubjectInfoAccess
extnValue = createExtnValueSubjectInfoAccess();
if (extnValue != null) {
ASN1ObjectIdentifier oid = Extension.subjectInfoAccess;
extensions.add(new Extension(oid, false, extnValue));
needExtensionTypes.add(oid.getId());
}
// Keyusage
if (isNotEmpty(keyusages)) {
Set<KeyUsage> usages = new HashSet<>();
for (String usage : keyusages) {
usages.add(KeyUsage.getKeyUsage(usage));
}
org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
ASN1ObjectIdentifier extType = Extension.keyUsage;
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
}
// ExtendedKeyusage
if (isNotEmpty(extkeyusages)) {
ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages));
ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
}
// QcEuLimitValue
if (isNotEmpty(qcEuLimits)) {
ASN1EncodableVector vec = new ASN1EncodableVector();
for (String m : qcEuLimits) {
StringTokenizer st = new StringTokenizer(m, ":");
try {
String currencyS = st.nextToken();
String amountS = st.nextToken();
String exponentS = st.nextToken();
Iso4217CurrencyCode currency;
try {
int intValue = Integer.parseInt(currencyS);
currency = new Iso4217CurrencyCode(intValue);
} catch (NumberFormatException ex) {
currency = new Iso4217CurrencyCode(currencyS);
}
int amount = Integer.parseInt(amountS);
int exponent = Integer.parseInt(exponentS);
MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent);
QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue, monterayValue);
vec.add(statment);
} catch (Exception ex) {
throw new Exception("invalid qc-eu-limit '" + m + "'");
}
}
ASN1ObjectIdentifier extType = Extension.qCStatements;
ASN1Sequence extValue = new DERSequence(vec);
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
}
// biometricInfo
if (biometricType != null && biometricHashAlgo != null && biometricFile != null) {
TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType) ? new TypeOfBiometricData(Integer.parseInt(biometricType)) : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType));
ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo);
byte[] biometricBytes = IoUtil.read(biometricFile);
MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId());
md.reset();
byte[] tmpBiometricDataHash = md.digest(biometricBytes);
DERIA5String tmpSourceDataUri = null;
if (biometricUri != null) {
tmpSourceDataUri = new DERIA5String(biometricUri);
}
BiometricData biometricData = new BiometricData(tmpBiometricType, new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash), tmpSourceDataUri);
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(biometricData);
ASN1ObjectIdentifier extType = Extension.biometricInfo;
ASN1Sequence extValue = new DERSequence(vec);
extensions.add(new Extension(extType, false, extValue.getEncoded()));
needExtensionTypes.add(extType.getId());
} else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) {
// Do nothing
} else {
throw new Exception("either all of biometric triples (type, hash algo, file)" + " must be set or none of them should be set");
}
for (Extension addExt : getAdditionalExtensions()) {
extensions.add(addExt);
}
needExtensionTypes.addAll(getAdditionalNeedExtensionTypes());
wantExtensionTypes.addAll(getAdditionalWantExtensionTypes());
if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes), textToAsn1ObjectIdentifers(wantExtensionTypes));
extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false, ee.toASN1Primitive().getEncoded()));
}
ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain, gm));
Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>();
if (CollectionUtil.isNonEmpty(extensions)) {
attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new Extensions(extensions.toArray(new Extension[0])));
}
if (StringUtil.isNotBlank(challengePassword)) {
attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword));
}
SubjectPublicKeyInfo subjectPublicKeyInfo;
if (signer.getCertificate() != null) {
Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded());
subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();
} else {
subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey());
}
X500Name subjectDn = getSubject(subject);
PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes);
File file = new File(outputFilename);
saveVerbose("saved CSR to file", file, csr.getEncoded());
return null;
}
use of org.spongycastle.asn1.x509.AlgorithmIdentifier in project xipki by xipki.
the class CaClientExample method generateRsaKeypair.
protected static MyKeypair generateRsaKeypair() throws Exception {
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
kpGen.initialize(2048);
KeyPair kp = kpGen.generateKeyPair();
RSAPublicKey pubKey = (RSAPublicKey) kp.getPublic();
SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new org.bouncycastle.asn1.pkcs.RSAPublicKey(pubKey.getModulus(), pubKey.getPublicExponent()));
return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
Aggregations