use of org.bouncycastle.asn1.ocsp.Signature in project xipki by xipki.
the class OcspStatusCmd method processResponse.
@Override
protected Object processResponse(OCSPResp response, X509Certificate respIssuer, IssuerHash issuerHash, List<BigInteger> serialNumbers, Map<BigInteger, byte[]> encodedCerts) throws Exception {
ParamUtil.requireNonNull("response", response);
ParamUtil.requireNonNull("issuerHash", issuerHash);
ParamUtil.requireNonNull("serialNumbers", serialNumbers);
BasicOCSPResp basicResp = OcspUtils.extractBasicOcspResp(response);
boolean extendedRevoke = basicResp.getExtension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke) != null;
SingleResp[] singleResponses = basicResp.getResponses();
if (singleResponses == null || singleResponses.length == 0) {
throw new CmdFailure("received no status from server");
}
final int n = singleResponses.length;
if (n != serialNumbers.size()) {
throw new CmdFailure("received status with " + n + " single responses from server, but " + serialNumbers.size() + " were requested");
}
Date[] thisUpdates = new Date[n];
for (int i = 0; i < n; i++) {
thisUpdates[i] = singleResponses[i].getThisUpdate();
}
// check the signature if available
if (null == basicResp.getSignature()) {
println("response is not signed");
} else {
X509CertificateHolder[] responderCerts = basicResp.getCerts();
if (responderCerts == null || responderCerts.length < 1) {
throw new CmdFailure("no responder certificate is contained in the response");
}
ResponderID respId = basicResp.getResponderId().toASN1Primitive();
X500Name respIdByName = respId.getName();
byte[] respIdByKey = respId.getKeyHash();
X509CertificateHolder respSigner = null;
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) {
throw new CmdFailure("no responder certificate match the ResponderId");
}
boolean validOn = true;
for (Date thisUpdate : thisUpdates) {
validOn = respSigner.isValidOn(thisUpdate);
if (!validOn) {
throw new CmdFailure("responder certificate is not valid on " + thisUpdate);
}
}
if (validOn) {
PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(responderPubKey);
boolean sigValid = basicResp.isSignatureValid(cvp);
if (!sigValid) {
throw new CmdFailure("response is equipped with invalid signature");
}
// verify the OCSPResponse signer
if (respIssuer != null) {
boolean certValid = true;
X509Certificate jceRespSigner = X509Util.toX509Cert(respSigner.toASN1Structure());
if (X509Util.issues(respIssuer, jceRespSigner)) {
try {
jceRespSigner.verify(respIssuer.getPublicKey());
} catch (SignatureException ex) {
certValid = false;
}
}
if (!certValid) {
throw new CmdFailure("response is equipped with valid signature but the" + " OCSP signer is not trusted");
}
} else {
println("response is equipped with valid signature");
}
// end if(respIssuer)
}
if (verbose.booleanValue()) {
println("responder is " + X509Util.getRfc4519Name(responderCerts[0].getSubject()));
}
}
for (int i = 0; i < n; i++) {
if (n > 1) {
println("---------------------------- " + i + "----------------------------");
}
SingleResp singleResp = singleResponses[i];
CertificateStatus singleCertStatus = singleResp.getCertStatus();
String status;
if (singleCertStatus == null) {
status = "good";
} else if (singleCertStatus instanceof RevokedStatus) {
RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
Date revTime = revStatus.getRevocationTime();
Date invTime = null;
Extension ext = singleResp.getExtension(Extension.invalidityDate);
if (ext != null) {
invTime = ASN1GeneralizedTime.getInstance(ext.getParsedValue()).getDate();
}
if (revStatus.hasRevocationReason()) {
int reason = revStatus.getRevocationReason();
if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTime.getTime() == 0) {
status = "unknown (RFC6960)";
} else {
status = StringUtil.concatObjects("revoked, reason = ", CrlReason.forReasonCode(reason).getDescription(), ", revocationTime = ", revTime, (invTime == null ? "" : ", invalidityTime = " + invTime));
}
} else {
status = "revoked, no reason, revocationTime = " + revTime;
}
} else if (singleCertStatus instanceof UnknownStatus) {
status = "unknown (RFC2560)";
} else {
status = "ERROR";
}
StringBuilder msg = new StringBuilder();
CertificateID certId = singleResp.getCertID();
HashAlgo hashAlgo = HashAlgo.getNonNullInstance(certId.getHashAlgOID());
boolean issuerMatch = issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash());
BigInteger serialNumber = certId.getSerialNumber();
msg.append("issuer matched: ").append(issuerMatch);
msg.append("\nserialNumber: ").append(LogUtil.formatCsn(serialNumber));
msg.append("\nCertificate status: ").append(status);
if (verbose.booleanValue()) {
msg.append("\nthisUpdate: ").append(singleResp.getThisUpdate());
msg.append("\nnextUpdate: ").append(singleResp.getNextUpdate());
Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
if (extension != null) {
msg.append("\nCertHash is provided:\n");
ASN1Encodable extensionValue = extension.getParsedValue();
CertHash certHash = CertHash.getInstance(extensionValue);
ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
byte[] hashValue = certHash.getCertificateHash();
msg.append("\tHash algo : ").append(hashAlgOid.getId()).append("\n");
msg.append("\tHash value: ").append(Hex.encode(hashValue)).append("\n");
if (encodedCerts != null) {
byte[] encodedCert = encodedCerts.get(serialNumber);
MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
byte[] expectedHashValue = md.digest(encodedCert);
if (Arrays.equals(expectedHashValue, hashValue)) {
msg.append("\tThis matches the requested certificate");
} else {
msg.append("\tThis differs from the requested certificate");
}
}
}
// end if (extension != null)
extension = singleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
if (extension != null) {
ASN1Encodable extensionValue = extension.getParsedValue();
ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(extensionValue);
msg.append("\nArchive-CutOff: ");
msg.append(time.getTimeString());
}
AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
if (sigAlg == null) {
msg.append(("\nresponse is not signed"));
} else {
String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
if (sigAlgName == null) {
sigAlgName = "unknown";
}
msg.append("\nresponse is signed with ").append(sigAlgName);
}
// extensions
msg.append("\nExtensions: ");
List<?> extensionOids = basicResp.getExtensionOIDs();
if (extensionOids == null || extensionOids.size() == 0) {
msg.append("-");
} else {
int size = extensionOids.size();
for (int j = 0; j < size; j++) {
ASN1ObjectIdentifier extensionOid = (ASN1ObjectIdentifier) extensionOids.get(j);
String name = EXTENSION_OIDNAME_MAP.get(extensionOid);
if (name == null) {
msg.append(extensionOid.getId());
} else {
msg.append(name);
}
if (j != size - 1) {
msg.append(", ");
}
}
}
}
// end if (verbose.booleanValue())
println(msg.toString());
}
// end for
println("");
return null;
}
use of org.bouncycastle.asn1.ocsp.Signature in project signer by demoiselle.
the class CAdESChecker method check.
/**
* Validation is done only on digital signatures with a single signer. Valid
* only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 =
* OID Data 1.2.840.113549.1.7.1
*
* @params content Is only necessary to inform if the PKCS7 package is NOT
* ATTACHED type. If it is of type attached, this parameter will be
* replaced by the contents of the PKCS7 package.
* @params signedData Value in bytes of the PKCS7 package, such as the
* contents of a ".p7s" file. It is not only signature as in the
* case of PKCS1.
*/
// TODO: Implementar validação de co-assinaturas
public boolean check(byte[] content, byte[] signedData) throws SignerException {
Security.addProvider(new BouncyCastleProvider());
CMSSignedData cmsSignedData = null;
try {
if (content == null) {
if (this.checkHash) {
cmsSignedData = new CMSSignedData(this.hashes, signedData);
this.checkHash = false;
} else {
cmsSignedData = new CMSSignedData(signedData);
}
} else {
cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData);
}
} catch (CMSException ex) {
throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex);
}
// Quantidade inicial de assinaturas validadas
int verified = 0;
Store<?> certStore = cmsSignedData.getCertificates();
SignerInformationStore signers = cmsSignedData.getSignerInfos();
Iterator<?> it = signers.getSigners().iterator();
// Realização da verificação básica de todas as assinaturas
while (it.hasNext()) {
SignatureInformations signatureInfo = new SignatureInformations();
try {
SignerInformation signerInfo = (SignerInformation) it.next();
SignerInformationStore signerInfoStore = signerInfo.getCounterSignatures();
logger.info("Foi(ram) encontrada(s) " + signerInfoStore.size() + " contra-assinatura(s).");
@SuppressWarnings("unchecked") Collection<?> certCollection = certStore.getMatches(signerInfo.getSID());
Iterator<?> certIt = certCollection.iterator();
X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();
X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
PeriodValidator pV = new PeriodValidator();
try {
pV.validate(varCert);
} catch (CertificateValidatorException cve) {
signatureInfo.getValidatorErrors().add(cve.getMessage());
}
CRLValidator cV = new CRLValidator();
try {
cV.validate(varCert);
} catch (CertificateValidatorCRLException cvce) {
signatureInfo.getValidatorErrors().add(cvce.getMessage());
}
if (signerInfo.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) {
verified++;
logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified));
}
// recupera atributos assinados
logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
AttributeTable signedAttributes = signerInfo.getSignedAttributes();
if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) {
signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
logger.info(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
} else {
// Validando atributos assinados de acordo com a politica
Attribute idSigningPolicy = null;
idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId()));
if (idSigningPolicy == null) {
signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "idSigningPolicy"));
} else {
for (Enumeration<?> p = idSigningPolicy.getAttrValues().getObjects(); p.hasMoreElements(); ) {
String policyOnSignature = p.nextElement().toString();
for (PolicyFactory.Policies pv : PolicyFactory.Policies.values()) {
if (policyOnSignature.contains(pv.getUrl())) {
setSignaturePolicy(pv);
break;
}
}
}
}
}
if (signaturePolicy == null) {
signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.policy.on.component.not.found", "idSigningPolicy"));
logger.info(cadesMessagesBundle.getString("error.policy.on.component.not.found", "idSigningPolicy"));
} else {
if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr().getObjectIdentifiers() != null) {
for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr().getObjectIdentifiers()) {
String oi = objectIdentifier.getValue();
Attribute signedAtt = signedAttributes.get(new ASN1ObjectIdentifier(oi));
logger.info(oi);
if (signedAtt == null) {
signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.signed.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue()));
}
}
}
}
// Mostra data e hora da assinatura, não é carimbo de tempo
Attribute timeAttribute = signedAttributes.get(CMSAttributes.signingTime);
Date dataHora = null;
if (timeAttribute != null) {
dataHora = (((ASN1UTCTime) timeAttribute.getAttrValues().getObjectAt(0)).getDate());
logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora));
} else {
logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D"));
signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("info.date.utc", "N/D"));
}
// recupera os atributos NÃO assinados
logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
AttributeTable unsignedAttributes = signerInfo.getUnsignedAttributes();
if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) {
// Apenas info pois a RB não tem atributos não assinados
logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found"));
}
if (signaturePolicy != null) {
// Validando atributos NÃO assinados de acordo com a politica
if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers() != null) {
for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers()) {
String oi = objectIdentifier.getValue();
Attribute unSignedAtt = unsignedAttributes.get(new ASN1ObjectIdentifier(oi));
logger.info(oi);
if (unSignedAtt == null) {
signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.unsigned.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue()));
}
if (oi.equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) {
// Verificando timeStamp
try {
byte[] varSignature = signerInfo.getSignature();
Timestamp varTimeStampSigner = validateTimestamp(unSignedAtt, varSignature);
signatureInfo.setTimeStampSigner(varTimeStampSigner);
} catch (Exception ex) {
signatureInfo.getValidatorErrors().add(ex.getMessage());
// nas assinaturas feitas na applet o unsignedAttributes.get gera exceção.
}
}
if (oi.equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) {
logger.info("++++++++++ EscTimeStamp ++++++++++++");
}
}
}
}
LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance().getCertificateChain(varCert);
if (varChain.size() < 3) {
signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN()));
logger.info(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN()));
}
signatureInfo.setSignDate(dataHora);
signatureInfo.setChain(varChain);
signatureInfo.setSignaturePolicy(signaturePolicy);
this.getSignaturesInfo().add(signatureInfo);
} catch (OperatorCreationException | java.security.cert.CertificateException ex) {
signatureInfo.getValidatorErrors().add(ex.getMessage());
logger.info(ex.getMessage());
} catch (CMSException ex) {
// When file is mismatch with sign
if (ex instanceof CMSSignerDigestMismatchException) {
signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.signature.mismatch"));
logger.info(cadesMessagesBundle.getString("error.signature.mismatch"));
} else {
signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.signature.invalid"));
logger.info(cadesMessagesBundle.getString("error.signature.invalid"));
}
} catch (ParseException e) {
signatureInfo.getValidatorErrors().add(e.getMessage());
logger.info(e.getMessage());
} catch (Exception e) {
signatureInfo.getValidatorErrors().add(e.getMessage());
logger.info(e.getMessage());
}
}
logger.info(cadesMessagesBundle.getString("info.signature.verified", verified));
// TODO Efetuar o parsing da estrutura CMS
return true;
}
use of org.bouncycastle.asn1.ocsp.Signature in project signer by demoiselle.
the class PolicyFactory method loadLPA.
/**
* @return LPA ICP Brasil signature policy v1
* @deprecated Politics DISCONTINUED
*/
@Deprecated
public LPA loadLPA() {
org.demoiselle.signer.policy.engine.asn1.icpb.LPA listaPoliticaAssinatura = new org.demoiselle.signer.policy.engine.asn1.icpb.LPA();
InputStream is = this.getClass().getResourceAsStream(ListOfSubscriptionPolicies.LPAV1.getFile());
ASN1Primitive primitive = this.readANS1FromStream(is);
listaPoliticaAssinatura.parse(primitive);
return listaPoliticaAssinatura;
}
use of org.bouncycastle.asn1.ocsp.Signature in project signer by demoiselle.
the class PolicyFactory method loadLPAPAdESUrl.
/**
* Load signature policy for PAdES standard (PDF) from url
* @return org.demoiselle.signer.policy.engine.asn1.icpb.v2.LPA
*/
public org.demoiselle.signer.policy.engine.asn1.icpb.v2.LPA loadLPAPAdESUrl() {
org.demoiselle.signer.policy.engine.asn1.icpb.v2.LPA listaPoliticaAssinatura = new org.demoiselle.signer.policy.engine.asn1.icpb.v2.LPA();
InputStream is;
try {
String conURL = ListOfSubscriptionPolicies.PAdES_URL.getUrl();
is = Downloads.getInputStreamFromURL(conURL);
ASN1Primitive primitive = this.readANS1FromStream(is);
is.close();
if (!LPARepository.saveLocalLPA(conURL, "LPA_PAdES.der")) {
LOGGER.warn(policyMessagesBundle.getString("error.lpa.not.saved", "LPA_PAdES.der"));
}
listaPoliticaAssinatura.parse(primitive);
} catch (RuntimeException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return listaPoliticaAssinatura;
}
use of org.bouncycastle.asn1.ocsp.Signature in project signer by demoiselle.
the class PolicyFactory method loadLPAv2.
/**
* @return LPA ICP Brasil signature policy v2
* @deprecated Politics DISCONTINUED 28/11/2016
*/
@Deprecated
public org.demoiselle.signer.policy.engine.asn1.icpb.v2.LPA loadLPAv2() {
org.demoiselle.signer.policy.engine.asn1.icpb.v2.LPA listaPoliticaAssinatura = new org.demoiselle.signer.policy.engine.asn1.icpb.v2.LPA();
InputStream is = this.getClass().getResourceAsStream(ListOfSubscriptionPolicies.LPAV2.getFile());
ASN1Primitive primitive = this.readANS1FromStream(is);
listaPoliticaAssinatura.parse(primitive);
return listaPoliticaAssinatura;
}
Aggregations