use of org.bouncycastle.util.Store 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;
}
use of org.bouncycastle.util.Store in project nhin-d by DirectProject.
the class CreateUnSignedPKCS7 method create.
/**
* Creates a pcks7 file from the certificate and key files.
* @param certFile The X509 DER encoded certificate file.
* @param keyFile The PCKS8 DER encoded private key file.
* @param password Option password for the private key file. This is required if the private key file is encrypted. Should be null or empty
* if the private key file is not encrypted.
* @param createFile Optional file descriptor for the output file of the pkcs12 file. If this is null, the file name is based on the
* certificate file name.
* @return File descriptor of the created pcks7 file. Null if an error occurred.
*/
public File create(String anchorDir, File createFile, File metaFile, boolean metaExists) {
File pkcs7File = null;
FileOutputStream outStr = null;
InputStream inStr = null;
// load cert file
try {
File userDir = new File(anchorDir);
File[] files = userDir.listFiles();
X509Certificate[] certs = new X509Certificate[files.length];
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
int counter = 0;
for (File certFile : files) {
if (certFile.isFile() && !certFile.isHidden()) {
if (certFile.getName().endsWith(".der")) {
byte[] certData = loadFileData(certFile);
certs[counter] = getX509Certificate(certData);
certList.add(certs[counter]);
counter++;
}
}
}
if (counter == 0) {
error = "Trust Anchors are not available in specified folder!";
return null;
}
byte[] metaDataByte;
if (metaExists) {
metaDataByte = loadFileData(metaFile);
} else {
metaDataByte = "Absent".getBytes();
}
CMSTypedData msg = new CMSProcessableByteArray(metaDataByte);
Store certStores = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
//SignedData data = new SignedData(arg0, arg1, arg2, arg3, arg4)
gen.addCertificates(certStores);
CMSSignedData sigData = gen.generate(msg, metaExists);
//System.out.println("Inside Unsigned area: Create File:"+createFile);
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;
}
use of org.bouncycastle.util.Store in project jmeter by apache.
the class SMIMEAssertion method verifySignature.
private static AssertionResult verifySignature(SMIMEAssertionTestElement testElement, SMIMESignedParser s, String name) throws CMSException {
AssertionResult res = new AssertionResult(name);
try {
Store certs = s.getCertificates();
SignerInformationStore signers = s.getSignerInfos();
Iterator<?> signerIt = signers.getSigners().iterator();
if (signerIt.hasNext()) {
SignerInformation signer = (SignerInformation) signerIt.next();
Iterator<?> certIt = certs.getMatches(signer.getSID()).iterator();
if (certIt.hasNext()) {
// the signer certificate
X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
if (testElement.isVerifySignature()) {
SignerInformationVerifier verifier = null;
try {
verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert);
} catch (OperatorCreationException e) {
log.error("Can't create a provider.", e);
}
if (verifier == null || !signer.verify(verifier)) {
res.setFailure(true);
res.setFailureMessage("Signature is invalid");
}
}
if (testElement.isSignerCheckConstraints()) {
StringBuilder failureMessage = new StringBuilder();
String serial = testElement.getSignerSerial();
if (!JOrphanUtils.isBlank(serial)) {
BigInteger serialNbr = readSerialNumber(serial);
if (!serialNbr.equals(cert.getSerialNumber())) {
res.setFailure(true);
failureMessage.append("Serial number ").append(serialNbr).append(" does not match serial from signer certificate: ").append(cert.getSerialNumber()).append("\n");
}
}
String email = testElement.getSignerEmail();
if (!JOrphanUtils.isBlank(email)) {
List<String> emailFromCert = getEmailFromCert(cert);
if (!emailFromCert.contains(email)) {
res.setFailure(true);
failureMessage.append("Email address \"").append(email).append("\" not present in signer certificate\n");
}
}
String subject = testElement.getSignerDn();
if (subject.length() > 0) {
final X500Name certPrincipal = cert.getSubject();
log.debug("DN from cert: {}", certPrincipal);
X500Name principal = new X500Name(subject);
log.debug("DN from assertion: {}", principal);
if (!principal.equals(certPrincipal)) {
res.setFailure(true);
failureMessage.append("Distinguished name of signer certificate does not match \"").append(subject).append("\"\n");
}
}
String issuer = testElement.getIssuerDn();
if (issuer.length() > 0) {
final X500Name issuerX500Name = cert.getIssuer();
log.debug("IssuerDN from cert: {}", issuerX500Name);
X500Name principal = new X500Name(issuer);
log.debug("IssuerDN from assertion: {}", principal);
if (!principal.equals(issuerX500Name)) {
res.setFailure(true);
failureMessage.append("Issuer distinguished name of signer certificate does not match \"").append(subject).append("\"\n");
}
}
if (failureMessage.length() > 0) {
res.setFailureMessage(failureMessage.toString());
}
}
if (testElement.isSignerCheckByFile()) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
try (InputStream fis = new FileInputStream(testElement.getSignerCertFile());
InputStream bis = new BufferedInputStream(fis)) {
X509CertificateHolder certFromFile = new JcaX509CertificateHolder((X509Certificate) cf.generateCertificate(bis));
if (!certFromFile.equals(cert)) {
res.setFailure(true);
res.setFailureMessage("Signer certificate does not match certificate " + testElement.getSignerCertFile());
}
} catch (IOException e) {
if (log.isDebugEnabled()) {
log.debug("Could not read cert file {}", testElement.getSignerCertFile(), e);
}
res.setFailure(true);
res.setFailureMessage("Could not read certificate file " + testElement.getSignerCertFile());
}
}
} else {
res.setFailure(true);
res.setFailureMessage("No signer certificate found in signature");
}
}
// TODO support multiple signers
if (signerIt.hasNext()) {
log.warn("SMIME message contains multiple signers! Checking multiple signers is not supported.");
}
} catch (GeneralSecurityException e) {
log.error(e.getMessage(), e);
res.setError(true);
res.setFailureMessage(e.getMessage());
}
return res;
}
Aggregations