List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers encryptedData
ASN1ObjectIdentifier encryptedData
To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers encryptedData.
Click Source Link
From source file:com.vvote.thirdparty.ximix.util.BLSKeyStore.java
License:Apache License
/** * Load the key store object from the passed in PKCS#12 encoding, using the passed in password. * * @param password the password to unlock the key store. * @param encoding the ASN.1 encoded bytes representing the PKCS#12 store. * @throws IOException on a parsing error. * @throws GeneralSecurityException if there's an exception decrypting the store. *//*www .j a v a 2 s . co m*/ public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException { try { PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding); InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder() .setProvider("BC").build(password); ContentInfo[] infos = pfx.getContentInfos(); for (int i = 0; i != infos.length; i++) { if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider); PKCS12SafeBag[] bags = dataFact.getSafeBags(); Attribute[] attributes = bags[0].getAttributes(); X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue(); String keyID = getKeyID(attributes); BLS01PublicKeyParameters publicKeyParameters = BLSPublicKeyFactory .createKey(cert.getSubjectPublicKeyInfo()); paramsMap.put(keyID, publicKeyParameters.getParameters()); sequenceNoMap.put(keyID, ASN1Integer.getInstance( cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue()) .getValue().intValue()); sharedPublicKeyMap.put(keyID, publicKeyParameters.getPk()); if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) { signingKeys.add(keyID); } } else { PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]); PKCS12SafeBag[] bags = dataFact.getSafeBags(); String keyID = getKeyID(bags[0].getAttributes()); PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue(); PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider); sharedPrivateKeyMap.put(keyID, ASN1Integer.getInstance(info.parsePrivateKey()).getValue()); } } } catch (PKCSException e) { throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e); } }
From source file:de.carne.certmgr.store.provider.bouncycastle.PKCS12Decoder.java
License:Open Source License
public Collection<Object> decode() throws IOException, PasswordRequiredException { for (ContentInfo contentInfo : this.pkcs12.getContentInfos()) { if (contentInfo.getContentType().equals(PKCSObjectIdentifiers.encryptedData)) { PKCS12SafeBagFactory bagFactory = null; PKCSException decryptException = null; while (bagFactory == null) { try { bagFactory = new PKCS12SafeBagFactory(contentInfo, getInputDecryptorProvider(decryptException)); } catch (PKCSException e) { decryptException = e; }//from www . j av a 2 s. co m } decodeBags(bagFactory.getSafeBags()); } else { PKCS12SafeBagFactory bagFactory = new PKCS12SafeBagFactory(contentInfo); decodeBags(bagFactory.getSafeBags()); } } return this.decoded; }
From source file:es.gob.afirma.applet.CMSInformation.java
License:Open Source License
/** * Método principal que obtiene la información a partir de un fichero firmado * de tipo CMS.// www .j a v a 2 s .com * @param data Objeto CMS. * @return Texto descriptivo del objeto CMS. * @throws IOException Si ocurre algún problema leyendo o escribiendo los datos * @throws AOInvalidFormatException Error de formato no válido. */ static String getInformation(final byte[] data) throws IOException, AOInvalidFormatException { 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(); // Contenido a obtener informacion final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final String datos; if (doi.equals(PKCSObjectIdentifiers.data)) { datos = AppletMessages.getString("CMSInformation.0") + SP + DATA + CR; //$NON-NLS-1$ } else if (doi.equals(PKCSObjectIdentifiers.digestedData)) { datos = getFromDigestedData(doj); } else if (doi.equals(PKCSObjectIdentifiers.encryptedData)) { datos = extractData(doj, TYPE_ENCRYPTED_DATA, AppletMessages.getString("CMSInformation.0") + SP + ENCRYPTED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$ } else if (doi.equals(PKCSObjectIdentifiers.signedData)) { datos = extractData(doj, TYPE_SIGNED_DATA, AppletMessages.getString("CMSInformation.0") + SP + SIGNED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$ } else if (doi.equals(PKCSObjectIdentifiers.envelopedData)) { datos = extractData(doj, TYPE_ENVELOPED_DATA, AppletMessages.getString("CMSInformation.0") + SP + ENVELOPED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$ } else if (doi.equals(PKCSObjectIdentifiers.signedAndEnvelopedData)) { datos = extractData(doj, TYPE_SIGNED_ENVELOPED_DATA, AppletMessages.getString("CMSInformation.0") + SP + SIGNED_ENVELOPED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$ } else if (doi.equals(PKCSObjectIdentifiers.id_ct_authData)) { datos = extractData(doj, TYPE_AUTHENTICATED_DATA, AppletMessages.getString("CMSInformation.0") + SP + AUTHENTICATED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$ } else if (doi.equals(PKCSObjectIdentifiers.id_ct_authEnvelopedData)) { datos = extractData(doj, TYPE_AUTHENTICATED_ENVELOPED_DATA, AppletMessages.getString("CMSInformation.0") + SP + AUTH_ENVELOPED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$ } else if (doi.equals(CMSObjectIdentifiers.compressedData)) { datos = getFromCompressedData(doj); } else { throw new AOInvalidFormatException( "Los datos introducidos no se corresponden con un tipo de objeto CMS soportado"); //$NON-NLS-1$ } return datos; }
From source file:es.gob.afirma.applet.CMSInformation.java
License:Open Source License
/** * Obtiene los datos de cifrado usados./* w w w .j a v a2 s. c om*/ * * @param datos informacion de los datos cifrados sin formatear. * @return informacion de los datos cifrados. */ private static String getEncryptedContentInfo(final EncryptedContentInfo datos) { String info = ""; //$NON-NLS-1$ //especificamos el tipo de contenido if (datos.getContentType().equals(PKCSObjectIdentifiers.encryptedData)) { info = info + TB + AppletMessages.getString("CMSInformation.0") + SP + ENCRYPTED_DATA + CR; //$NON-NLS-1$ } else { info = info + TB + AppletMessages.getString("CMSInformation.0") + SP + datos.getContentType() + CR; //$NON-NLS-1$ } // el algoritmo de cifrado de los datos final AlgorithmIdentifier ai = datos.getContentEncryptionAlgorithm(); AOCipherAlgorithm algorithm = null; final AOCipherAlgorithm[] algos = AOCipherAlgorithm.values(); // obtenemos el algoritmo usado para cifrar la pass for (final AOCipherAlgorithm algo : algos) { if (algo.getOid().equals(ai.getAlgorithm().toString())) { algorithm = algo; } } if (algorithm != null) { info = info + TB + AppletMessages.getString("CMSInformation.17") + SP + algorithm.getName() + CR; //$NON-NLS-1$ } else { info = info + TB + AppletMessages.getString("CMSInformation.18") + SP + ai.getAlgorithm().toString() //$NON-NLS-1$ + CR; } return info; }
From source file:es.gob.afirma.envelopers.cades.CAdESEncryptedData.java
License:Open Source License
/** Método principal que genera la firma de tipo EncryptedData. * @param data//from ww w .j a v a 2 s .co m * Datos a cifrar. * @param digAlg * ALgoritmo para realizar el Digest. * @param config * Configuración del algoritmo para firmar. * @param pass * Cadena que se usar paa cifrar los datos. * @param dataType * Identifica el tipo del contenido a firmar. * @return la firma de tipo EncryptedData. * @throws java.security.NoSuchAlgorithmException * Si no se soporta alguno de los algoritmos de firma o huella * digital * @throws IOException */ static byte[] genEncryptedData(final byte[] data, final String digAlg, final AOCipherConfig config, final String pass, final String dataType) throws NoSuchAlgorithmException, AOException, IOException { // Asignamos la clave de cifrado final SecretKey cipherKey = CAdESUtils.assignKey(config, pass); // Datos previos útiles final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(digAlg); // generamos el contenedor de cifrado final EncryptedContentInfo encInfo; try { // 3. ENCRIPTEDCONTENTINFO encInfo = CAdESUtils.getEncryptedContentInfo(data, config, cipherKey); } catch (final Exception ex) { throw new AOException("Error durante el proceso de cifrado", ex); //$NON-NLS-1$ } // 4. ATRIBUTOS // obtenemos la lista de certificados final ASN1Set unprotectedAttrs = SigUtils.getAttributeSet( new AttributeTable(CAdESUtils.initContexExpecific(digestAlgorithm, data, dataType, null))); // construimos el Enveloped Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.encryptedData, new EncryptedData(encInfo, unprotectedAttrs)) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cades.CAdESUtils.java
License:Open Source License
/** Obtiene el contenido de un archivo encriptado * @param file Archivo con los datos// w ww .j a va 2s. c o m * @param config Configuracion de cifrado * @param params Parametros * @param cipher Encriptador */ private static EncryptedContentInfo getEncryptedContentInfo(final byte[] file, final AOCipherConfig config, final AlgorithmParameterSpec params, final Cipher cipher) throws IOException { final byte[] ciphered; try { ciphered = cipher.doFinal(file); } catch (final Exception e) { LOGGER.severe("No se ha podido completar el cifrado, se devolvera null: " + e); //$NON-NLS-1$ return null; } ASN1Encodable asn1Params; if (params != null) { final ASN1InputStream aIn = new ASN1InputStream(cipher.getParameters().getEncoded("ASN.1")); //$NON-NLS-1$ asn1Params = aIn.readObject(); aIn.close(); } else { asn1Params = new DERNull(); } // obtenemos el OID del algoritmo de cifrado final AlgorithmIdentifier encAlgId = new AlgorithmIdentifier( new ASN1ObjectIdentifier(config.getAlgorithm().getOid()), asn1Params); // Obtenemos el identificador final ASN1ObjectIdentifier contentType = PKCSObjectIdentifiers.encryptedData; return new EncryptedContentInfo(contentType, encAlgId, new DEROctetString(ciphered)); }
From source file:es.gob.afirma.envelopers.cms.AOCMSEnveloper.java
License:Open Source License
/** Recupera el contenido de un envoltorio CMS. * @param cmsEnvelop Envoltorio CMS./*from www. ja v a 2s. c om*/ * @param addresseePke Clave privada del destinatario que desea desensobrar. * @return Contenido del envoltorio. * @throws InvalidKeyException Cuando la clave de descifrado configurada no sea válida o pertenezca a un destinatario. * @throws AOException Cuando se produce un error durante al desenvolver los datos. * @throws InvalidKeySpecException Cuando ocurren problemas relacionados con la estructura interna de las claves */ @Override public byte[] recoverData(final byte[] cmsEnvelop, final PrivateKeyEntry addresseePke) throws InvalidKeyException, AOException, IOException, InvalidKeySpecException { final org.bouncycastle.asn1.ASN1InputStream is = new org.bouncycastle.asn1.ASN1InputStream(cmsEnvelop); // Leemos los datos final org.bouncycastle.asn1.ASN1Sequence dsq = (org.bouncycastle.asn1.ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> objects = dsq.getObjects(); // Elementos que contienen los elementos OID Data final org.bouncycastle.asn1.ASN1ObjectIdentifier doi = (org.bouncycastle.asn1.ASN1ObjectIdentifier) objects .nextElement(); byte[] datos; try { if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.data)) { Logger.getLogger("es.gob.afirma") //$NON-NLS-1$ .warning("La extraccion de datos de los envoltorios CMS Data no esta implementada"); //$NON-NLS-1$ datos = null; } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.digestedData)) { Logger.getLogger("es.gob.afirma") //$NON-NLS-1$ .warning("La extraccion de datos de los envoltorios CMS DigestedData no esta implementada"); //$NON-NLS-1$ datos = null; } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.compressedData)) { datos = AOCMSEnveloper.recoverCMSCompressedData(cmsEnvelop); } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.encryptedData)) { datos = AOCMSEnveloper.recoverCMSEncryptedData(cmsEnvelop, this.cipherKey); } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.envelopedData)) { datos = AOCMSEnveloper.recoverCMSEnvelopedData(cmsEnvelop, addresseePke); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authEnvelopedData)) { datos = AOCMSEnveloper.recoverCMSAuthenticatedEnvelopedData(cmsEnvelop, addresseePke); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authenticatedData)) { datos = AOCMSEnveloper.recoverCMSAuthenticatedData(cmsEnvelop, addresseePke); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.signedAndEnvelopedData)) { datos = AOCMSEnveloper.recoverCMSSignedEnvelopedData(cmsEnvelop, addresseePke); } else { throw new AOInvalidFormatException( "Los datos introducidos no se corresponden con un tipo de objeto CMS soportado"); //$NON-NLS-1$ } } catch (final AOInvalidRecipientException e) { throw new InvalidKeyException( "La clave indicada no pertenece a ninguno de los destinatarios del envoltorio", e); //$NON-NLS-1$ } catch (final CertificateEncodingException e) { throw new AOException("Error al descodificar los certificados del envoltorio", e); //$NON-NLS-1$ } catch (final NoSuchAlgorithmException e) { throw new AOException("No se reconoce el algoritmo indicado", e); //$NON-NLS-1$ } catch (final NoSuchPaddingException e) { throw new AOException("No se reconoce el tipo de relleno indicado", e); //$NON-NLS-1$ } catch (final InvalidAlgorithmParameterException e) { throw new AOException("No se reconoce la configuracion del algoritmo indicado", e); //$NON-NLS-1$ } catch (final IllegalBlockSizeException e) { throw new AOException("Tamano de bloque invalido: " + e, e); //$NON-NLS-1$ } catch (final BadPaddingException e) { throw new AOException("relleno invalido: " + e, e); //$NON-NLS-1$ } return datos; }
From source file:es.gob.afirma.envelopers.cms.AOCMSMultiEnveloper.java
License:Open Source License
/** Recupera el contenido de un envoltorio CMS. * @param cmsEnvelop/*from ww w . j a va 2s . c o m*/ * Envoltorio CMS. * @return Contenido del envoltorio. * @throws AOInvalidRecipientException * Cuando el usuario no es uno de los destinatarios del sobre. * @throws InvalidKeyException Cuando la clave de descifrado configurada no es válida. * @throws CertificateEncodingException * Cuando el certificado del destinatario no es válido. * @throws IOException * Cuando el envoltorio está corrupto o no puede leerse. * @throws AOInvalidFormatException * Cuando no se ha indicado un envoltorio soportado. * @throws AOException * Cuando se produce un error durante al desenvolver los datos. * @throws NoSuchAlgorithmException Si el JRE no soporta algún algoritmo necesario * @throws BadPaddingException Si hay problemas estableciendo el relleno de los datos * @throws IllegalBlockSizeException Si no cuadran los tamaños de bloque de los algoritmos usados * @throws InvalidAlgorithmParameterException Si no se soporta algún parámetro necesario * para algún algoritmo * @throws NoSuchPaddingException Si no se soporta algún método de relleno * @throws InvalidKeySpecException Cuando ocurren problemas relacionados con la estructura interna de las claves */ byte[] recoverData(final byte[] cmsEnvelop) throws InvalidKeyException, CertificateEncodingException, IOException, AOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException { final org.bouncycastle.asn1.ASN1InputStream is = new org.bouncycastle.asn1.ASN1InputStream(cmsEnvelop); // Leemos los datos final org.bouncycastle.asn1.ASN1Sequence dsq = (org.bouncycastle.asn1.ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> objects = dsq.getObjects(); // Elementos que contienen los elementos OID Data final org.bouncycastle.asn1.ASN1ObjectIdentifier doi = (org.bouncycastle.asn1.ASN1ObjectIdentifier) objects .nextElement(); byte[] datos; if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.data)) { LOGGER.warning("La extraccion de datos de los envoltorios CMS Data no esta implementada"); //$NON-NLS-1$ datos = null; } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.digestedData)) { LOGGER.warning("La extraccion de datos de los envoltorios CMS DigestedData no esta implementada"); //$NON-NLS-1$ datos = null; } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.compressedData)) { datos = AOCMSMultiEnveloper.recoverCMSCompressedData(cmsEnvelop); } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.encryptedData)) { datos = AOCMSMultiEnveloper.recoverCMSEncryptedData(cmsEnvelop, this.cipherKey); } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.envelopedData)) { datos = AOCMSMultiEnveloper.recoverCMSEnvelopedData(cmsEnvelop, this.configuredKe); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authEnvelopedData)) { datos = AOCMSMultiEnveloper.recoverCMSAuthenticatedEnvelopedData(cmsEnvelop, this.configuredKe); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authenticatedData)) { datos = AOCMSMultiEnveloper.recoverCMSAuthenticatedData(cmsEnvelop, this.configuredKe); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.signedAndEnvelopedData)) { datos = AOCMSMultiEnveloper.recoverCMSSignedEnvelopedData(cmsEnvelop, this.configuredKe); } else { throw new AOInvalidFormatException( "Los datos introducidos no se corresponden con un tipo de objeto CMS soportado"); //$NON-NLS-1$ } return datos; }
From source file:es.gob.afirma.envelopers.cms.CMSEncryptedData.java
License:Open Source License
/** Método principal que genera la firma de tipo EncryptedData. * @param data//from w ww .j av a2 s.co m * Datos que queremos envolver. * @param digAlg * Algoritmo para realizar el Digest. * @param config * Configuración del algoritmo para cifrar. * @param cipherKey * Clave de cifrado. * @param dataType * Identifica el tipo del contenido a firmar. * @param uatrib * Conjunto de atributos no firmados. * @return la firma de tipo EncryptedData. * @throws java.security.NoSuchAlgorithmException * Si no se soporta alguno de los algoritmos de firma o huella * digital * @throws IOException * Cuando se produce algun error al codificar los datos. */ static byte[] genEncryptedData(final byte[] data, final String digAlg, final AOCipherConfig config, final Key cipherKey, final String dataType, final Map<String, byte[]> uatrib) throws NoSuchAlgorithmException, IOException { // Datos previos útiles final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(digAlg); // generamos el contenedor de cifrado EncryptedContentInfo encInfo = null; try { // 3. ENCRIPTEDCONTENTINFO encInfo = Utils.getEncryptedContentInfo(data, cipherKey, config); } catch (final Exception ex) { Logger.getLogger("es.gob.afirma").severe("Error durante el proceso cifrado: " + ex); //$NON-NLS-1$ //$NON-NLS-2$ } // 4. ATRIBUTOS // obtenemos la lista de certificados ASN1Set unprotectedAttrs = null; unprotectedAttrs = Utils.generateSignerInfo(digestAlgorithm, data, dataType, uatrib); // construimos el Enveloped Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.encryptedData, new EncryptedData(encInfo, unprotectedAttrs)) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cms.Utils.java
License:Open Source License
/** Obtiene el contenido de un archivo encriptado. * @param file Archivo con los datos// www. j av a2 s .co m * @param config Configuracion de cifrado * @param params Parametros * @param cipher Encriptador * @return Contenido de un archivo encriptado. * @throws BadPaddingException Cuando hay problemas con un relleno de datos. * @throws IOException Cuando hay problemas con el tratamiento de datos. * @throws IllegalBlockSizeException Cuando hay problemas internos con los tamaños de bloque de cifrado. */ private static EncryptedContentInfo getEncryptedContentInfo(final byte[] file, final AOCipherConfig config, final AlgorithmParameterSpec params, final Cipher cipher) throws IOException, IllegalBlockSizeException, BadPaddingException { ASN1Encodable asn1Params; if (params != null) { final ASN1InputStream aIn = new ASN1InputStream(cipher.getParameters().getEncoded("ASN.1")); //$NON-NLS-1$ asn1Params = aIn.readObject(); aIn.close(); } else { asn1Params = DERNull.INSTANCE; } // obtenemos el OID del algoritmo de cifrado final AlgorithmIdentifier encAlgId = new AlgorithmIdentifier( new ASN1ObjectIdentifier(config.getAlgorithm().getOid()), asn1Params); // Obtenemos el identificador final ASN1ObjectIdentifier contentType = PKCSObjectIdentifiers.encryptedData; return new EncryptedContentInfo(contentType, encAlgId, new DEROctetString(cipher.doFinal(file))); }