use of org.bouncycastle.cms.CMSProcessable in project sic by belluccifranco.
the class AfipWebServiceSOAPClient method crearCMS.
public byte[] crearCMS(byte[] p12file, String p12pass, String signer, String service, long ticketTime) {
PrivateKey pKey = null;
X509Certificate pCertificate = null;
byte[] asn1_cms = null;
CertStore cstore = null;
try {
KeyStore ks = KeyStore.getInstance("pkcs12");
InputStream is;
is = Utilidades.convertirByteArrayToInputStream(p12file);
ks.load(is, p12pass.toCharArray());
is.close();
pKey = (PrivateKey) ks.getKey(signer, p12pass.toCharArray());
pCertificate = (X509Certificate) ks.getCertificate(signer);
ArrayList<X509Certificate> certList = new ArrayList<>();
certList.add(pCertificate);
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
}
cstore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | InvalidAlgorithmParameterException | NoSuchProviderException ex) {
LOGGER.error(ex.getMessage());
throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_certificado_error"));
}
String loginTicketRequest_xml = this.crearTicketRequerimientoAcceso(service, ticketTime);
try {
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addSigner(pKey, pCertificate, CMSSignedDataGenerator.DIGEST_SHA1);
generator.addCertificatesAndCRLs(cstore);
CMSProcessable data = new CMSProcessableByteArray(loginTicketRequest_xml.getBytes());
CMSSignedData signed = generator.generate(data, true, "BC");
asn1_cms = signed.getEncoded();
} catch (IllegalArgumentException | CertStoreException | CMSException | NoSuchAlgorithmException | NoSuchProviderException | IOException ex) {
LOGGER.error(ex.getMessage());
throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_firmando_certificado_error"));
}
return asn1_cms;
}
use of org.bouncycastle.cms.CMSProcessable in project athenz by yahoo.
the class Crypto method validatePKCS7Signature.
// /CLOVER:OFF
public static boolean validatePKCS7Signature(String data, String signature, PublicKey publicKey) {
try {
SignerInformationStore signerStore;
try (InputStream sigIs = new ByteArrayInputStream(Base64.decode(signature.getBytes(StandardCharsets.UTF_8)))) {
CMSProcessable content = new CMSProcessableByteArray(data.getBytes(StandardCharsets.UTF_8));
CMSSignedData signedData = new CMSSignedData(content, sigIs);
signerStore = signedData.getSignerInfos();
}
Collection<SignerInformation> signers = signerStore.getSigners();
Iterator<SignerInformation> it = signers.iterator();
SignerInformationVerifier infoVerifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC_PROVIDER).build(publicKey);
while (it.hasNext()) {
SignerInformation signerInfo = it.next();
if (signerInfo.verify(infoVerifier)) {
return true;
}
}
} catch (CMSException ex) {
LOG.error("validatePKCS7Signature: unable to initialize CMSSignedData object: {}", ex.getMessage());
throw new CryptoException(ex);
} catch (OperatorCreationException ex) {
LOG.error("validatePKCS7Signature: Caught OperatorCreationException when creating JcaSimpleSignerInfoVerifierBuilder: {}", ex.getMessage());
throw new CryptoException(ex);
} catch (IOException ex) {
LOG.error("validatePKCS7Signature: Caught IOException when closing InputStream: {}", ex.getMessage());
throw new CryptoException(ex);
} catch (Exception ex) {
LOG.error("validatePKCS7Signature: unable to validate signature: {}", ex.getMessage());
throw new CryptoException(ex.getMessage());
}
return false;
}
use of org.bouncycastle.cms.CMSProcessable in project pdfbox by apache.
the class ShowSignature method verifyPKCS7.
/**
* Verify a PKCS7 signature.
*
* @param signedContentAsStream the byte sequence that has been signed
* @param contents the /Contents field as a COSString
* @param sig the PDF signature (the /V dictionary)
* @throws CMSException
* @throws OperatorCreationException
* @throws GeneralSecurityException
* @throws CertificateVerificationException
*/
private void verifyPKCS7(InputStream signedContentAsStream, byte[] contents, PDSignature sig) throws CMSException, OperatorCreationException, CertificateVerificationException, GeneralSecurityException, TSPException, IOException {
// inspiration:
// http://stackoverflow.com/a/26702631/535646
// http://stackoverflow.com/a/9261365/535646
CMSProcessable signedContent = new CMSProcessableInputStream(signedContentAsStream);
CMSSignedData signedData = new CMSSignedData(signedContent, contents);
Store<X509CertificateHolder> certificatesStore = signedData.getCertificates();
if (certificatesStore.getMatches(null).isEmpty()) {
throw new IOException("No certificates in signature");
}
Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
if (signers.isEmpty()) {
throw new IOException("No signers in signature");
}
SignerInformation signerInformation = signers.iterator().next();
@SuppressWarnings("unchecked") Collection<X509CertificateHolder> matches = certificatesStore.getMatches(signerInformation.getSID());
if (matches.isEmpty()) {
throw new IOException("Signer '" + signerInformation.getSID().getIssuer() + ", serial# " + signerInformation.getSID().getSerialNumber() + " does not match any certificates");
}
X509CertificateHolder certificateHolder = matches.iterator().next();
X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
System.out.println("certFromSignedData: " + certFromSignedData);
SigUtils.checkCertificateUsage(certFromSignedData);
// Embedded timestamp
TimeStampToken timeStampToken = SigUtils.extractTimeStampTokenFromSignerInformation(signerInformation);
if (timeStampToken != null) {
// tested with QV_RCA1_RCA3_CPCPS_V4_11.pdf
// https://www.quovadisglobal.com/~/media/Files/Repository/QV_RCA1_RCA3_CPCPS_V4_11.ashx
// also 021496.pdf and 036351.pdf from digitalcorpora
SigUtils.validateTimestampToken(timeStampToken);
X509Certificate certFromTimeStamp = SigUtils.getCertificateFromTimeStampToken(timeStampToken);
// merge both stores using a set to remove duplicates
HashSet<X509CertificateHolder> certificateHolderSet = new HashSet<>();
certificateHolderSet.addAll(certificatesStore.getMatches(null));
certificateHolderSet.addAll(timeStampToken.getCertificates().getMatches(null));
SigUtils.verifyCertificateChain(new CollectionStore<>(certificateHolderSet), certFromTimeStamp, timeStampToken.getTimeStampInfo().getGenTime());
SigUtils.checkTimeStampCertificateUsage(certFromTimeStamp);
// compare the hash of the signature with the hash in the timestamp
byte[] tsMessageImprintDigest = timeStampToken.getTimeStampInfo().getMessageImprintDigest();
String hashAlgorithm = timeStampToken.getTimeStampInfo().getMessageImprintAlgOID().getId();
byte[] sigMessageImprintDigest = MessageDigest.getInstance(hashAlgorithm).digest(signerInformation.getSignature());
if (Arrays.equals(tsMessageImprintDigest, sigMessageImprintDigest)) {
System.out.println("timestamp signature verified");
} else {
System.err.println("timestamp signature verification failed");
}
}
try {
if (sig.getSignDate() != null) {
certFromSignedData.checkValidity(sig.getSignDate().getTime());
System.out.println("Certificate valid at signing time");
} else {
System.err.println("Certificate cannot be verified without signing time");
}
} catch (CertificateExpiredException ex) {
System.err.println("Certificate expired at signing time");
} catch (CertificateNotYetValidException ex) {
System.err.println("Certificate not yet valid at signing time");
}
// usually not available
if (signerInformation.getSignedAttributes() != null) {
// From SignedMailValidator.getSignatureTime()
Attribute signingTime = signerInformation.getSignedAttributes().get(CMSAttributes.signingTime);
if (signingTime != null) {
Time timeInstance = Time.getInstance(signingTime.getAttrValues().getObjectAt(0));
try {
certFromSignedData.checkValidity(timeInstance.getDate());
System.out.println("Certificate valid at signing time: " + timeInstance.getDate());
} catch (CertificateExpiredException ex) {
System.err.println("Certificate expired at signing time");
} catch (CertificateNotYetValidException ex) {
System.err.println("Certificate not yet valid at signing time");
}
}
}
if (signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(SecurityProvider.getProvider()).build(certFromSignedData))) {
System.out.println("Signature verified");
} else {
System.out.println("Signature verification failed");
}
if (CertificateVerifier.isSelfSigned(certFromSignedData)) {
System.err.println("Certificate is self-signed, LOL!");
} else {
System.out.println("Certificate is not self-signed");
if (sig.getSignDate() != null) {
SigUtils.verifyCertificateChain(certificatesStore, certFromSignedData, sig.getSignDate().getTime());
} else {
System.err.println("Certificate cannot be verified without signing time");
}
}
}
Aggregations