use of org.bouncycastle.cms.CMSProcessableByteArray in project nhin-d by DirectProject.
the class DefaultBundleRefreshProcessorImpl method convertRawBundleToAnchorCollection.
/**
* Converts a trust raw trust bundle byte array into a collection of {@link X509Certificate} objects.
* @param rawBundle The raw representation of the bundle. This generally the raw byte string downloaded from the bundle's URL.
* @param existingBundle The configured bundle object in the DAO. This object may contain the signing certificate
* used for bundle authenticity checking.
* @param processAttempStart The time that the update process started.
* @return
*/
@SuppressWarnings("unchecked")
protected Collection<X509Certificate> convertRawBundleToAnchorCollection(byte[] rawBundle, final TrustBundle existingBundle, final Calendar processAttempStart) {
Collection<? extends Certificate> bundleCerts = null;
InputStream inStream = null;
// check to see if its an unsigned PKCS7 container
try {
inStream = new ByteArrayInputStream(rawBundle);
bundleCerts = CertificateFactory.getInstance("X.509").generateCertificates(inStream);
// if its null and has no anchors, then try again as a signed bundle
if (bundleCerts != null && bundleCerts.size() == 0)
bundleCerts = null;
} catch (Exception e) {
/* no-op for now.... this may not be a p7b, so try it as a signed message*/
} finally {
IOUtils.closeQuietly(inStream);
}
// didnt work... try again as a CMS signed message
if (bundleCerts == null) {
try {
final CMSSignedData signed = new CMSSignedData(rawBundle);
// then verify the signature
if (existingBundle.getSigningCertificateData() != null) {
boolean sigVerified = false;
final X509Certificate signingCert = existingBundle.toSigningCertificate();
for (SignerInformation sigInfo : (Collection<SignerInformation>) signed.getSignerInfos().getSigners()) {
try {
if (sigInfo.verify(signingCert, CryptoExtensions.getJCEProviderName())) {
sigVerified = true;
break;
}
} catch (Exception e) {
/* no-op... can't verify */
}
}
if (!sigVerified) {
dao.updateLastUpdateError(existingBundle.getId(), processAttempStart, BundleRefreshError.UNMATCHED_SIGNATURE);
log.warn("Downloaded bundle signature did not match configured signing certificate.");
return null;
}
}
final CMSProcessableByteArray signedContent = (CMSProcessableByteArray) signed.getSignedContent();
inStream = new ByteArrayInputStream((byte[]) signedContent.getContent());
bundleCerts = CertificateFactory.getInstance("X.509").generateCertificates(inStream);
} catch (Exception e) {
dao.updateLastUpdateError(existingBundle.getId(), processAttempStart, BundleRefreshError.INVALID_BUNDLE_FORMAT);
log.warn("Failed to extract anchors from downloaded bundle at URL " + existingBundle.getBundleURL());
} finally {
IOUtils.closeQuietly(inStream);
}
}
return (Collection<X509Certificate>) bundleCerts;
}
use of org.bouncycastle.cms.CMSProcessableByteArray 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.CMSProcessableByteArray in project athenz by yahoo.
the class Crypto method validatePKCS7Signature.
public static boolean validatePKCS7Signature(String data, String signature, PublicKey publicKey) {
try {
SignerInformationStore signerStore = null;
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 = (SignerInformation) 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;
}
Aggregations