use of org.bouncycastle.cms.CMSException 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.cms.CMSException in project nhin-d by DirectProject.
the class SplitDirectRecipientInformation method getContentStream.
/**
* {@inheritDoc}
*/
@Override
public CMSTypedStream getContentStream(Key key, /*private key*/
String prov) throws /*ignored, use class variables instead*/
CMSException, NoSuchProviderException {
// this is the symmetric key
final byte[] encryptedKey = info.getEncryptedKey().getOctets();
// this is the algorithm that protects the symmetric key
final String keyExchangeAlgorithm = getExchangeEncryptionAlgorithmName(_keyEncAlg.getObjectId());
// this is the algorithm of the symmetric key to actually decrypt the content
final String alg = EncryptionAlgorithm.fromOID(_encAlg.getObjectId().getId(), EncryptionAlgorithm.AES128_CBC).getAlgName();
try {
Cipher keyCipher = Cipher.getInstance(keyExchangeAlgorithm, keyEncProvider);
Key sKey;
try {
// the original BC libraries attempted to do an UNWRAP assuming that the
// same provider was used for secret key decryption and message decryption
// when these two operations are split into separate providers, using an unwrap method
// may result in a secret key handle that may not be usable by the another provider
// for that reason, this class will do a straight up decrypt of the message's internal
// secret key and hand that key off to the "encProvider" provider
keyCipher.init(Cipher.DECRYPT_MODE, key);
sKey = new SecretKeySpec(keyCipher.doFinal(encryptedKey), alg);
} catch (GeneralSecurityException e) {
keyCipher.init(Cipher.DECRYPT_MODE, key);
sKey = new SecretKeySpec(keyCipher.doFinal(encryptedKey), alg);
} catch (IllegalStateException e) {
keyCipher.init(Cipher.DECRYPT_MODE, key);
sKey = new SecretKeySpec(keyCipher.doFinal(encryptedKey), alg);
} catch (UnsupportedOperationException e) {
keyCipher.init(Cipher.DECRYPT_MODE, key);
sKey = new SecretKeySpec(keyCipher.doFinal(encryptedKey), alg);
} catch (ProviderException e) {
keyCipher.init(Cipher.DECRYPT_MODE, key);
sKey = new SecretKeySpec(keyCipher.doFinal(encryptedKey), alg);
}
return getContentFromSessionKey(sKey, encProvider);
} catch (NoSuchAlgorithmException e) {
throw new CMSException("can't find algorithm.", e);
} catch (InvalidKeyException e) {
throw new CMSException("key invalid in message.", e);
} catch (NoSuchPaddingException e) {
throw new CMSException("required padding not supported.", e);
} catch (IllegalBlockSizeException e) {
throw new CMSException("illegal blocksize in message.", e);
} catch (BadPaddingException e) {
throw new CMSException("bad padding in message.", e);
}
}
use of org.bouncycastle.cms.CMSException in project nhin-d by DirectProject.
the class SplitProviderDirectSignedDataGenerator method generate.
/**
* {@inheritDoc}
*/
@Override
public CMSSignedData generate(String signedContentType, CMSProcessable content, boolean encapsulate, String sigProvider, boolean addDefaultAttributes) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException {
final ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
final ASN1EncodableVector signerInfos = new ASN1EncodableVector();
// clear the current preserved digest state
_digests.clear();
//
// add the SignerInfo objects
//
DERObjectIdentifier contentTypeOID;
boolean isCounterSignature;
if (signedContentType != null) {
contentTypeOID = new DERObjectIdentifier(signedContentType);
isCounterSignature = false;
} else {
contentTypeOID = CMSObjectIdentifiers.data;
isCounterSignature = true;
}
for (DirectTargetedSignerInf signer : privateSigners) {
AlgorithmIdentifier digAlgId;
try {
digAlgId = new AlgorithmIdentifier(new DERObjectIdentifier(signer.digestOID), new DERNull());
digestAlgs.add(digAlgId);
try {
signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, sigProvider, digestProvider, addDefaultAttributes, isCounterSignature));
} catch (ClassCastException e) {
// try again with the digest provider... the key may need to use a different provider than the sig provider
signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, digestProvider, digestProvider, addDefaultAttributes, isCounterSignature));
}
} catch (IOException e) {
throw new CMSException("encoding error.", e);
} catch (InvalidKeyException e) {
throw new CMSException("key inappropriate for signature.", e);
} catch (SignatureException e) {
throw new CMSException("error creating signature.", e);
} catch (CertificateEncodingException e) {
throw new CMSException("error creating sid.", e);
}
}
ASN1Set certificates = null;
if (_certs.size() != 0) {
certificates = createBerSetFromList(_certs);
}
ASN1Set certrevlist = null;
if (_crls.size() != 0) {
certrevlist = createBerSetFromList(_crls);
}
ContentInfo encInfo;
if (encapsulate) {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try {
content.write(bOut);
} catch (IOException e) {
throw new CMSException("encapsulation error.", e);
}
ASN1OctetString octs = new BERConstructedOctetString(bOut.toByteArray());
encInfo = new ContentInfo(contentTypeOID, octs);
} else {
encInfo = new ContentInfo(contentTypeOID, null);
}
SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos));
ContentInfo contentInfo = new ContentInfo(PKCSObjectIdentifiers.signedData, sd);
return new CMSSignedData(content, contentInfo);
}
use of org.bouncycastle.cms.CMSException in project tika by apache.
the class Pkcs7Parser method parse.
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {
try {
DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
CMSSignedDataParser parser = new CMSSignedDataParser(digestCalculatorProvider, new CloseShieldInputStream(stream));
try {
CMSTypedStream content = parser.getSignedContent();
if (content == null) {
throw new TikaException("cannot parse detached pkcs7 signature (no signed data to parse)");
}
try (InputStream input = content.getContentStream()) {
Parser delegate = context.get(Parser.class, EmptyParser.INSTANCE);
delegate.parse(input, handler, metadata, context);
}
} finally {
parser.close();
}
} catch (OperatorCreationException e) {
throw new TikaException("Unable to create DigestCalculatorProvider", e);
} catch (CMSException e) {
throw new TikaException("Unable to parse pkcs7 signed data", e);
}
}
use of org.bouncycastle.cms.CMSException 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;
}
Aggregations