use of org.bouncycastle.asn1.cms.SignedData in project robovm by robovm.
the class CMSSignedDataGenerator method generate.
public CMSSignedData generate(// FIXME Avoid accessing more than once to support CMSProcessableInputStream
CMSTypedData content, boolean encapsulate) throws CMSException {
if (!signerInfs.isEmpty()) {
throw new IllegalStateException("this method can only be used with SignerInfoGenerator");
}
// TODO
// if (signerInfs.isEmpty())
// {
// /* RFC 3852 5.2
// * "In the degenerate case where there are no signers, the
// * EncapsulatedContentInfo value being "signed" is irrelevant. In this
// * case, the content type within the EncapsulatedContentInfo value being
// * "signed" MUST be id-data (as defined in section 4), and the content
// * field of the EncapsulatedContentInfo value MUST be omitted."
// */
// if (encapsulate)
// {
// throw new IllegalArgumentException("no signers, encapsulate must be false");
// }
// if (!DATA.equals(eContentType))
// {
// throw new IllegalArgumentException("no signers, eContentType must be id-data");
// }
// }
//
// if (!DATA.equals(eContentType))
// {
// /* RFC 3852 5.3
// * [The 'signedAttrs']...
// * field is optional, but it MUST be present if the content type of
// * the EncapsulatedContentInfo value being signed is not id-data.
// */
// // TODO signedAttrs must be present for all signers
// }
ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
ASN1EncodableVector signerInfos = new ASN1EncodableVector();
// clear the current preserved digest state
digests.clear();
//
for (Iterator it = _signers.iterator(); it.hasNext(); ) {
SignerInformation signer = (SignerInformation) it.next();
digestAlgs.add(CMSSignedHelper.INSTANCE.fixAlgID(signer.getDigestAlgorithmID()));
// TODO Verify the content type and calculated digest match the precalculated SignerInfo
signerInfos.add(signer.toASN1Structure());
}
//
// add the SignerInfo objects
//
ASN1ObjectIdentifier contentTypeOID = content.getContentType();
ASN1OctetString octs = null;
if (content != null) {
ByteArrayOutputStream bOut = null;
if (encapsulate) {
bOut = new ByteArrayOutputStream();
}
OutputStream cOut = CMSUtils.attachSignersToOutputStream(signerGens, bOut);
// Just in case it's unencapsulated and there are no signers!
cOut = CMSUtils.getSafeOutputStream(cOut);
try {
content.write(cOut);
cOut.close();
} catch (IOException e) {
throw new CMSException("data processing exception: " + e.getMessage(), e);
}
if (encapsulate) {
octs = new BEROctetString(bOut.toByteArray());
}
}
for (Iterator it = signerGens.iterator(); it.hasNext(); ) {
SignerInfoGenerator sGen = (SignerInfoGenerator) it.next();
SignerInfo inf = sGen.generate(contentTypeOID);
digestAlgs.add(inf.getDigestAlgorithm());
signerInfos.add(inf);
byte[] calcDigest = sGen.getCalculatedDigest();
if (calcDigest != null) {
digests.put(inf.getDigestAlgorithm().getAlgorithm().getId(), calcDigest);
}
}
ASN1Set certificates = null;
if (certs.size() != 0) {
certificates = CMSUtils.createBerSetFromList(certs);
}
ASN1Set certrevlist = null;
if (crls.size() != 0) {
certrevlist = CMSUtils.createBerSetFromList(crls);
}
ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);
SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos));
ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
return new CMSSignedData(content, contentInfo);
}
use of org.bouncycastle.asn1.cms.SignedData in project robovm by robovm.
the class CertificateFactory method engineGenerateCRLs.
/**
* Returns a (possibly empty) collection view of the CRLs read from
* the given input stream inStream.
*
* The inStream may contain a sequence of DER-encoded CRLs, or
* a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the
* only signficant field being crls. In particular the signature
* and the contents are ignored.
*/
public Collection engineGenerateCRLs(InputStream inStream) throws CRLException {
CRL crl;
List crls = new ArrayList();
while ((crl = engineGenerateCRL(inStream)) != null) {
crls.add(crl);
}
return crls;
}
use of org.bouncycastle.asn1.cms.SignedData in project XobotOS by xamarin.
the class PKIXCertPath method getEncoded.
/**
* Returns the encoded form of this certification path, using
* the specified encoding.
*
* @param encoding the name of the encoding to use
* @return the encoded bytes
* @exception CertificateEncodingException if an encoding error
* occurs or the encoding requested is not supported
*
**/
public byte[] getEncoded(String encoding) throws CertificateEncodingException {
if (encoding.equalsIgnoreCase("PkiPath")) {
ASN1EncodableVector v = new ASN1EncodableVector();
ListIterator iter = certificates.listIterator(certificates.size());
while (iter.hasPrevious()) {
v.add(toASN1Object((X509Certificate) iter.previous()));
}
return toDEREncoded(new DERSequence(v));
} else if (encoding.equalsIgnoreCase("PKCS7")) {
ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null);
ASN1EncodableVector v = new ASN1EncodableVector();
for (int i = 0; i != certificates.size(); i++) {
v.add(toASN1Object((X509Certificate) certificates.get(i)));
}
SignedData sd = new SignedData(new DERInteger(1), new DERSet(), encInfo, new DERSet(v), null, new DERSet());
return toDEREncoded(new ContentInfo(PKCSObjectIdentifiers.signedData, sd));
} else // BEGIN android-removed
// else if (encoding.equalsIgnoreCase("PEM"))
// {
// ByteArrayOutputStream bOut = new ByteArrayOutputStream();
// PEMWriter pWrt = new PEMWriter(new OutputStreamWriter(bOut));
//
// try
// {
// for (int i = 0; i != certificates.size(); i++)
// {
// pWrt.writeObject(certificates.get(i));
// }
//
// pWrt.close();
// }
// catch (Exception e)
// {
// throw new CertificateEncodingException("can't encode certificate for PEM encoded path");
// }
//
// return bOut.toByteArray();
// }
// END android-removed
{
throw new CertificateEncodingException("unsupported encoding: " + encoding);
}
}
use of org.bouncycastle.asn1.cms.SignedData in project nhin-d by DirectProject.
the class ViewTrustBundlePKCS7 method viewBundle.
@SuppressWarnings({ "rawtypes" })
public boolean viewBundle(File trustDir) {
try {
//System.out.println("File:"+trustDir.getName());
if (!trustDir.getName().endsWith(".p7m")) {
byte[] trustBundleByte = loadFileData(trustDir);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
ContentInfo contentInfo = dataParser.getContentInfo();
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
Enumeration certificates = signedData.getCertificates().getObjects();
StringBuffer output = new StringBuffer();
int counter = 1;
String chk = "Absent";
while (certificates.hasMoreElements()) {
DERObject certObj = (DERObject) certificates.nextElement();
InputStream in = new ByteArrayInputStream(certObj.getDEREncoded());
X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
output.append("Trust Anchor :" + counter + "\n");
output.append("Common Name :" + IETFUtils.valueToString(cn.getFirst().getValue()) + "\n");
output.append("DN :" + cert.getSubjectDN().getName() + "\n\n");
counter++;
}
if (signedData.getEncapContentInfo().getContent() != null) {
//chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8");
chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getDEREncoded(), "UTF-8");
}
output.append("Meta Data :\n" + chk);
error = output.toString();
} else //end of if check of file type
{
StringBuffer output = new StringBuffer();
int counter = 1;
String chk = "Absent";
byte[] trustBundleByte = loadFileData(trustDir);
CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
ContentInfo contentInfo = dataParser.getContentInfo();
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
CMSSignedData encapInfoBundle = new CMSSignedData(new CMSProcessableByteArray(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded()), contentInfo);
SignedData encapMetaData = SignedData.getInstance(encapInfoBundle.getContentInfo().getContent());
//System.out.println("ENCAP META DATA"+new String(encapMetaData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8"));
CMSProcessableByteArray cin = new CMSProcessableByteArray(((ASN1OctetString) encapMetaData.getEncapContentInfo().getContent()).getOctets());
CertificateFactory ucf = CertificateFactory.getInstance("X.509");
CMSSignedData unsignedParser = new CMSSignedData(cin.getInputStream());
ContentInfo unsginedEncapInfo = unsignedParser.getContentInfo();
SignedData metaData = SignedData.getInstance(unsginedEncapInfo.getContent());
Enumeration certificates = metaData.getCertificates().getObjects();
while (certificates.hasMoreElements()) {
DERObject certObj = (DERObject) certificates.nextElement();
InputStream bin = new ByteArrayInputStream(certObj.getDEREncoded());
X509Certificate cert = (X509Certificate) ucf.generateCertificate(bin);
X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
output.append("Trust Anchor :" + counter + "\n");
output.append("Common Name :" + IETFUtils.valueToString(cn.getFirst().getValue()) + "\n");
output.append("DN :" + cert.getSubjectDN().getName() + "\n\n");
counter++;
}
if (metaData.getEncapContentInfo().getContent() != null) {
//chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8");
chk = new String(metaData.getEncapContentInfo().getContent().getDERObject().getDEREncoded(), "UTF-8");
}
output.append("Meta Data :\n" + chk);
error = output.toString();
}
//end of .p7m check if
}//end of try
catch (IOException io) {
//io.printStackTrace(System.err);
return false;
} catch (CMSException cm) {
//cm.printStackTrace(System.err);
return false;
} catch (Exception e) {
//e.printStackTrace(System.err);
return false;
}
return true;
}
use of org.bouncycastle.asn1.cms.SignedData in project ddf by codice.
the class KeystoreEditor method addToStore.
private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data, String type, String fileName, String path, String storepass, KeyStore store) throws KeystoreEditorException {
OutputStream fos = null;
try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
if (StringUtils.isBlank(alias)) {
throw new IllegalArgumentException("Alias cannot be null.");
}
Path storeFile = Paths.get(path);
//check the two most common key/cert stores first (pkcs12 and jks)
if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
//priv key + cert chain
KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
pkcs12Store.load(inputStream, storePassword.toCharArray());
Certificate[] chain = pkcs12Store.getCertificateChain(alias);
Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
if (key != null) {
store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
}
} else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
//java keystore file
KeyStore jks = KeyStore.getInstance("jks");
jks.load(inputStream, storePassword.toCharArray());
Enumeration<String> aliases = jks.aliases();
//we are going to store all entries from the jks regardless of the passed in alias
while (aliases.hasMoreElements()) {
String jksAlias = aliases.nextElement();
if (jks.isKeyEntry(jksAlias)) {
Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
} else {
Certificate certificate = jks.getCertificate(jksAlias);
store.setCertificateEntry(jksAlias, certificate);
}
}
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
//need to parse der separately from pem, der has the same mime type but is binary hence checking both
} else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
ASN1Primitive asn1Primitive = asn1InputStream.readObject();
X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
store.setCertificateEntry(cnStr, certificate);
}
store.setCertificateEntry(alias, certificate);
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
//if it isn't one of the stores we support, it might be a key or cert by itself
} else if (isPemParsable(type, fileName)) {
//This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
PEMParser pemParser = new PEMParser(reader);
Object object;
boolean setEntry = false;
while ((object = pemParser.readObject()) != null) {
if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
PEMKeyPair pemKeyPair;
if (object instanceof PEMEncryptedKeyPair) {
PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
} else {
pemKeyPair = (PEMKeyPair) object;
}
KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
PrivateKey privateKey = keyPair.getPrivate();
Certificate[] chain = store.getCertificateChain(alias);
if (chain == null) {
chain = buildCertChain(alias, store);
}
store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
setEntry = true;
} else if (object instanceof X509CertificateHolder) {
X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
store.setCertificateEntry(cnStr, certificate);
}
store.setCertificateEntry(alias, certificate);
setEntry = true;
} else if (object instanceof ContentInfo) {
ContentInfo contentInfo = (ContentInfo) object;
if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
ASN1Set certificates = originatorInfo.getCertificates();
setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
} else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
ASN1Set certificates = signedData.getCertificates();
setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
}
} else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
Certificate[] chain = store.getCertificateChain(alias);
if (chain == null) {
chain = buildCertChain(alias, store);
}
try {
store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
setEntry = true;
} catch (KeyStoreException keyEx) {
try {
PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(), keyPassword.toCharArray());
store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(), chain);
setEntry = true;
} catch (GeneralSecurityException e) {
LOGGER.info("Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.", e);
throw keyEx;
}
}
}
}
if (setEntry) {
fos = Files.newOutputStream(storeFile);
store.store(fos, storepass.toCharArray());
}
}
} catch (Exception e) {
LOGGER.info("Unable to add entry {} to store", alias, e);
throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ignore) {
}
}
}
init();
}
Aggregations