use of org.demoiselle.signer.policy.impl.cades.SignerException in project signer by demoiselle.
the class CAdESChecker method validateTimestamp.
/**
* validade a timestampo on signature
* @param attributeTimeStamp
* @param varSignature
* @return
*/
private Timestamp validateTimestamp(Attribute attributeTimeStamp, byte[] varSignature) {
try {
TimeStampOperator timeStampOperator = new TimeStampOperator();
byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
Timestamp timeStampSigner = new Timestamp(timeStampToken);
timeStampOperator.validate(varSignature, varTimeStamp, null);
return timeStampSigner;
} catch (CertificateCoreException | IOException | TSPException | CMSException e) {
throw new SignerException(e);
}
}
use of org.demoiselle.signer.policy.impl.cades.SignerException in project signer by demoiselle.
the class CAdESChecker method getAttached.
/**
* Extracts the signed content from the digital signature structure, if it
* is a signature with attached content.
*
* @param signed
* Signature and signed content.
* @param validateOnExtract
* TRUE (to execute validation) or FALSE (not execute validation)
*
* @return content for attached signature
*/
@Override
public byte[] getAttached(byte[] signed, boolean validateOnExtract) {
byte[] result = null;
if (validateOnExtract) {
this.check(null, signed);
}
CMSSignedData signedData = null;
try {
signedData = new CMSSignedData(signed);
} catch (CMSException exception) {
throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), exception);
}
try {
CMSProcessable contentProcessable = signedData.getSignedContent();
if (contentProcessable != null) {
result = (byte[]) contentProcessable.getContent();
}
} catch (Exception exception) {
throw new SignerException(cadesMessagesBundle.getString("error.get.content.pkcs7"), exception);
}
return result;
}
use of org.demoiselle.signer.policy.impl.cades.SignerException 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.demoiselle.signer.policy.impl.cades.SignerException in project signer by demoiselle.
the class RevocationRefs method getValue.
@Override
public Attribute getValue() throws SignerException {
try {
int chainSize = certificates.length - 1;
ArrayList<CrlValidatedID> crls = new ArrayList<CrlValidatedID>();
for (int ix = 0; ix < chainSize; ix++) {
X509Certificate cert = (X509Certificate) certificates[ix];
Collection<ICPBR_CRL> icpCrls = crlRepository.getX509CRL(cert);
for (ICPBR_CRL icpCrl : icpCrls) {
crls.add(makeCrlValidatedID(icpCrl.getCRL()));
}
}
int crlsIdSize = crls.size();
CrlValidatedID[] crlsForId = new CrlValidatedID[crlsIdSize];
int i = 0;
for (CrlValidatedID crlVID : crls) {
crlsForId[i] = crlVID;
i++;
}
// CrlListID crlids = new CrlListID(crlsForId);
DERSequence crlValidatedIDSeq = new DERSequence(crlsForId);
// --CRLListID--/
ASN1Encodable[] crlValidatedIDSeqArr = new ASN1Encodable[1];
crlValidatedIDSeqArr[0] = crlValidatedIDSeq;
DERSequence crlListID = new DERSequence(crlValidatedIDSeqArr);
// CRLListID--/
DERTaggedObject crlListIDTagged = new DERTaggedObject(0, crlListID);
// CrlOcspRef--/
ASN1Encodable[] crlListIDTaggedArr = new ASN1Encodable[1];
crlListIDTaggedArr[0] = crlListIDTagged;
DERSequence crlOscpRef = new DERSequence(crlListIDTaggedArr);
// --CompleteRevocationRefs--/
ASN1Encodable[] crlOscpRefArr = new ASN1Encodable[1];
crlOscpRefArr[0] = crlOscpRef;
DERSequence completeRevocationRefs = new DERSequence(crlOscpRefArr);
// CrlOcspRef crlOcspRef = new CrlOcspRef(crlids, null, null);
return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(completeRevocationRefs));
// CrlOcspRef[] crlOcspRefArray = new
// CrlOcspRef[completeRevocationRefs.size()];
} catch (NoSuchAlgorithmException | CRLException e) {
throw new SignerException(e.getMessage());
}
}
use of org.demoiselle.signer.policy.impl.cades.SignerException in project signer by demoiselle.
the class SigningCertificate method getValue.
@Override
public Attribute getValue() {
try {
X509Certificate cert = (X509Certificate) certificates[0];
Digest digest = DigestFactory.getInstance().factoryDefault();
digest.setAlgorithm(DigestAlgorithmEnum.SHA_1);
byte[] hash = digest.digest(cert.getEncoded());
X500Name dirName = new X500Name(cert.getSubjectDN().getName());
GeneralName name = new GeneralName(dirName);
GeneralNames issuer = new GeneralNames(name);
ASN1Integer serial = new ASN1Integer(cert.getSerialNumber());
IssuerSerial issuerSerial = new IssuerSerial(issuer, serial);
ESSCertID essCertId = new ESSCertID(hash, issuerSerial);
return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[] { new DERSequence(essCertId), new DERSequence(DERNull.INSTANCE) })));
} catch (CertificateEncodingException ex) {
throw new SignerException(ex.getMessage());
}
}
Aggregations