List of usage examples for org.bouncycastle.asn1.cms OriginatorInfo getCertificates
public ASN1Set getCertificates()
From source file:es.gob.afirma.envelopers.cms.CMSAuthenticatedData.java
License:Open Source License
/** Método que inserta remitentes en el "OriginatorInfo" de un sobre * de tipo AuthenticatedData.//w ww. j a va2 s. co m * @param data * fichero que tiene la firma. * @param signerCertificateChain * Cadena de certificados a agregar. * @return La nueva firma AuthenticatedData con los remitentes que * tenía (si los tuviera) con la cadena de certificados * nueva. * @throws IOException Si hay errores de lectura o escritura de datos * @throws CertificateEncodingException Si el certificado del remitente es invalido */ static byte[] addOriginatorInfo(final InputStream data, final X509Certificate[] signerCertificateChain) throws IOException, CertificateEncodingException { final ASN1InputStream is = new ASN1InputStream(data); // LEEMOS EL FICHERO QUE NOS INTRODUCEN final ASN1Sequence dsq = (ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID Data final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement(); if (doi.equals(PKCSObjectIdentifiers.id_ct_authData)) { // Contenido de Data final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final AuthenticatedData auth = AuthenticatedData.getInstance(doj.getObject()); final AlgorithmIdentifier digAlg = extractAOIfromAuth((ASN1Sequence) doj.getObject()); // Obtenemos los originatorInfo OriginatorInfo origInfo = auth.getOriginatorInfo(); ASN1Set certs = null; if (origInfo != null) { certs = origInfo.getCertificates(); } final OriginatorInfo origInfoChecked = Utils.checkCertificates(signerCertificateChain, certs); if (origInfoChecked != null) { origInfo = origInfoChecked; } // Se crea un nuevo AuthenticatedData a partir de los datos // anteriores con los nuevos originantes. return new ContentInfo(PKCSObjectIdentifiers.id_ct_authData, new AuthenticatedData(origInfo, // OriginatorInfo auth.getRecipientInfos(), // ASN1Set auth.getMacAlgorithm(), // macAlgorithm digAlg, // AlgorithmIdentifier se les ha olvidado a BC implementar el getDigestAlgorithm auth.getEncapsulatedContentInfo(), // ContentInfo auth.getAuthAttrs(), // ASN1Set auth.getMac(), // ASN1OctetString auth.getUnauthAttrs() // ASN1Set )).getEncoded(ASN1Encoding.DER); } return null; }
From source file:es.gob.afirma.envelopers.cms.CMSAuthenticatedEnvelopedData.java
License:Open Source License
/** Método que inserta remitentes en el "OriginatorInfo" de un sobre * de tipo AuthenticatedEnvelopedData./*from ww w. java2 s . com*/ * @param data * Datos CMS de tipo AuthenticatedEnvelopedData. * @param signerCertificateChain * Cadena de certificados a agregar. * @return La nueva firma AuthenticatedEnvelopedData con los remitentes que * tenía (si los tuviera) con la cadena de certificados * nueva. * @throws IOException Cuando hay errores de lectura o escritura de datos * @throws CertificateEncodingException Si hay algún certificado inválido en la cadena */ public static byte[] addOriginatorInfo(final byte[] data, final X509Certificate[] signerCertificateChain) throws IOException, CertificateEncodingException { final ASN1InputStream is = new ASN1InputStream(data); // LEEMOS EL FICHERO QUE NOS INTRODUCEN final ASN1Sequence dsq = (ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID Data final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement(); if (doi.equals(PKCSObjectIdentifiers.id_ct_authEnvelopedData)) { // Contenido de Data final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final AuthEnvelopedData authEnv = AuthEnvelopedData.getInstance(doj.getObject()); // Obtenemos los originatorInfo OriginatorInfo origInfo = authEnv.getOriginatorInfo(); ASN1Set certs = null; if (origInfo != null) { certs = origInfo.getCertificates(); } final OriginatorInfo origInfoChecked = Utils.checkCertificates(signerCertificateChain, certs); if (origInfoChecked != null) { origInfo = origInfoChecked; } // Se crea un nuevo AuthenticatedEnvelopedData a partir de los // datos anteriores con los nuevos originantes. return new ContentInfo(PKCSObjectIdentifiers.id_ct_authEnvelopedData, new AuthEnvelopedData(origInfo, // OriginatorInfo authEnv.getRecipientInfos(), // ASN1Set authEnv.getAuthEncryptedContentInfo(), authEnv.getAuthAttrs(), authEnv.getMac(), authEnv.getUnauthAttrs())).getEncoded(ASN1Encoding.DER); } return null; }
From source file:es.gob.afirma.envelopers.cms.CMSEnvelopedData.java
License:Open Source License
/** Método que inserta remitentes en el "OriginatorInfo" de un sobre * de tipo envelopedData./*from w w w . jav a 2 s . co m*/ * @param data * Datos CMS que admiten multiples remitentes/firmantes. * @param signerCertificateChain * Cadena de certificados a agregar. * @return La nueva firma enveloped con los remitentes que tenía (si * los tuviera) con la cadena de certificados nueva. * @throws IOException Si hay errores de lectura de datos * @throws CertificateEncodingException Cuando el certificado proporcionado es inválido */ public static byte[] addOriginatorInfo(final byte[] data, final X509Certificate[] signerCertificateChain) throws IOException, CertificateEncodingException { final ASN1InputStream is = new ASN1InputStream(data); // LEEMOS EL FICHERO QUE NOS INTRODUCEN final ASN1Sequence dsq = (ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID Data final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement(); if (doi.equals(PKCSObjectIdentifiers.envelopedData)) { // Contenido de Data final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final EnvelopedData ed = EnvelopedData.getInstance(doj.getObject()); // Obtenemos los originatorInfo OriginatorInfo origInfo = ed.getOriginatorInfo(); ASN1Set certs = null; if (origInfo != null) { certs = origInfo.getCertificates(); } // Si no hay certificados, se deja como esta. final OriginatorInfo origInfoChecked = Utils.checkCertificates(signerCertificateChain, certs); if (origInfoChecked != null) { origInfo = origInfoChecked; } // Se crea un nuevo EnvelopedData a partir de los datos // anteriores con los nuevos originantes. return new ContentInfo(PKCSObjectIdentifiers.envelopedData, new EnvelopedData(origInfo, ed.getRecipientInfos(), ed.getEncryptedContentInfo(), ed.getUnprotectedAttrs())) .getEncoded(ASN1Encoding.DER); } return null; }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java
License:Open Source License
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;/*from w w w . j av a 2 s. c om*/ 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(); }