use of org.bouncycastle.cms.CMSException in project signer by demoiselle.
the class CAdESSigner 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.
*/
@SuppressWarnings("unchecked")
// TODO: Implementar validação de co-assinaturas
@Override
@Deprecated
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()) {
try {
SignerInformation signer = (SignerInformation) it.next();
SignerInformationStore s = signer.getCounterSignatures();
SignatureInformations si = new SignatureInformations();
logger.info("Foi(ram) encontrada(s) " + s.size() + " contra-assinatura(s).");
Collection<?> certCollection = certStore.getMatches(signer.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) {
si.getValidatorErrors().add(cve.getMessage());
}
CRLValidator cV = new CRLValidator();
try {
cV.validate(varCert);
} catch (CertificateValidatorCRLException cvce) {
si.getValidatorErrors().add(cvce.getMessage());
}
if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) {
verified++;
logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified));
}
// Realiza a verificação dos atributos assinados
logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
AttributeTable signedAttributes = signer.getSignedAttributes();
if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) {
throw new SignerException(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
}
// Realiza a verificação dos atributos não assinados
logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) {
logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found"));
}
// Mostra data e hora da assinatura, não é carimbo de tempo
Attribute signingTime = signedAttributes.get(CMSAttributes.signingTime);
Date dataHora = null;
if (signingTime != null) {
dataHora = (((ASN1UTCTime) signingTime.getAttrValues().getObjectAt(0)).getDate());
logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora));
} else {
logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D"));
}
logger.info(cadesMessagesBundle.getString("info.attribute.validation"));
// Valida o atributo ContentType
Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType);
if (attributeContentType == null) {
throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
}
if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
throw new SignerException(cadesMessagesBundle.getString("error.content.not.data"));
}
// Validando o atributo MessageDigest
Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest);
if (attributeMessageDigest == null) {
throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest"));
}
// Validando o atributo MessageDigest
Attribute idSigningPolicy = null;
idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId()));
if (idSigningPolicy == null) {
throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "idSigningPolicy"));
}
// Verificando timeStamp
try {
Attribute attributeTimeStamp = null;
attributeTimeStamp = unsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
if (attributeTimeStamp != null) {
byte[] varSignature = signer.getSignature();
Timestamp varTimeStampSigner = validateTimestamp(attributeTimeStamp, varSignature);
si.setTimeStampSigner(varTimeStampSigner);
}
} catch (Exception ex) {
// nas assinaturas feitas na applet o unsignedAttributes.get gera exceção.
}
LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance().getCertificateChain(varCert);
si.setSignDate(dataHora);
si.setChain(varChain);
si.setSignaturePolicy(signaturePolicy);
this.getSignatureInfo().add(si);
} catch (OperatorCreationException | java.security.cert.CertificateException ex) {
throw new SignerException(ex);
} catch (CMSException ex) {
// When file is mismatch with sign
if (ex instanceof CMSSignerDigestMismatchException)
throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex);
else
throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex);
} catch (ParseException e) {
throw new SignerException(e);
}
}
logger.info(cadesMessagesBundle.getString("info.signature.verified", verified));
// TODO Efetuar o parsing da estrutura CMS
return true;
}
use of org.bouncycastle.cms.CMSException in project signer by demoiselle.
the class CAdESSigner 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.bouncycastle.cms.CMSException in project signer by demoiselle.
the class CAdESSigner method validateTimestamp.
/**
* validade a timestampo on signature
* @param attributeTimeStamp
* @param varSignature
* @return
*/
@Deprecated
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.bouncycastle.cms.CMSException in project signer by demoiselle.
the class TimeStampOperator method validate.
/**
* Validate a time stamp
*
* @param content if it is assigned, the parameter hash must to be null
* @param timeStamp timestamp to be validated
* @param hash if it is assigned, the parameter content must to be null
* @throws CertificateCoreException validate exception
*/
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
try {
TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
CMSSignedData s = timeStampToken.toCMSSignedData();
int verified = 0;
Store<?> certStore = s.getCertificates();
SignerInformationStore signers = s.getSignerInfos();
Collection<SignerInformation> c = signers.getSigners();
Iterator<SignerInformation> it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = it.next();
Collection<?> certCollection = certStore.getMatches(signer.getSID());
Iterator<?> certIt = certCollection.iterator();
X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
verified++;
}
cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
}
logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified));
// Valida o hash incluso no carimbo de tempo com hash do arquivo carimbado
byte[] calculatedHash = null;
if (content != null) {
Digest digest = DigestFactory.getInstance().factoryDefault();
digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
calculatedHash = digest.digest(content);
} else {
calculatedHash = hash;
}
if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
} else {
throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
}
} catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
throw new CertificateCoreException(ex.getMessage());
}
}
use of org.bouncycastle.cms.CMSException in project nhin-d by DirectProject.
the class CreateSignedPKCS7 method create.
/**
* Creates a pcks7 file from the certificate and key files.
* @param anchorDir :The Directory where the .der files are present.
* @param createFile : The .p7m File name.
* @param metaFile :One XML file as per required specification of TrustBundle metadata schema.
* @param p12certiFile : The .p12 file.
* @param passkey :Pass Key for the .p12 file if present or else it should be blank.
* @param destDir : The Destination folder where the output .p7m files will be created.
* * @return File : Returns the created SignedBundle as a .p7m file.
*/
public File create(String anchorDir, File createFile, File metaFile, boolean metaExists, File p12certiFile, String passKey) {
File pkcs7File = null;
FileOutputStream outStr = null;
InputStream inStr = null;
try {
// Create the unsigned Trust Bundle
CreateUnSignedPKCS7 unSignedPKCS7 = new CreateUnSignedPKCS7();
File unsigned = unSignedPKCS7.create(anchorDir, createFile, metaFile, metaExists);
byte[] unsignedByte = loadFileData(unsigned);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
CMSSignedData unsignedData = new CMSSignedData(unsignedByte);
// Create the certificate array
KeyStore ks = java.security.KeyStore.getInstance("PKCS12", "BC");
ks.load(new FileInputStream(p12certiFile), defaultPwd.toCharArray());
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
String alias = (String) aliases.nextElement();
if (ks.getKey(alias, defaultPwd.toCharArray()) != null && ks.getKey(alias, defaultPwd.toCharArray()) instanceof PrivateKey) {
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build((PrivateKey) ks.getKey(alias, defaultPwd.toCharArray()));
X509CertificateHolder holder = new X509CertificateHolder(ks.getCertificate(alias).getEncoded());
certList.add((X509Certificate) ks.getCertificate(alias));
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, holder));
}
}
Store certStores = new JcaCertStore(certList);
gen.addCertificates(certStores);
CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(unsignedData.getEncoded()), true);
//SignedData encapInfo = SignedData.getInstance(sigData.getContentInfo().getContent());
pkcs7File = getPKCS7OutFile(createFile);
outStr = new FileOutputStream(pkcs7File);
outStr.write(sigData.getEncoded());
} catch (CMSException e) {
// e.printStackTrace(System.err);
return null;
} catch (IOException e) {
// e.printStackTrace(System.err);
return null;
} catch (KeyStoreException e) {
// e.printStackTrace(System.err);
return null;
} catch (NoSuchProviderException e) {
// e.printStackTrace(System.err);
return null;
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace(System.err);
return null;
} catch (CertificateException e) {
// e.printStackTrace(System.err);
return null;
} catch (UnrecoverableKeyException e) {
// e.printStackTrace(System.err);
return null;
} catch (OperatorCreationException e) {
// e.printStackTrace(System.err);
return null;
} catch (Exception e) {
// e.printStackTrace(System.err);
return null;
} finally {
IOUtils.closeQuietly(outStr);
IOUtils.closeQuietly(inStr);
}
return pkcs7File;
}
Aggregations