1

I have seen a lot of examples where you can use SMIME to encrypt and email but there is not examples to encrypt a regular file. I have a method where I insert the keys in a bd but I don't know how to use SMIME by bouncycastle to encrypt a file.

public CifradoDeArchivos obtenerCifradoDeArchivosParticular(
            ParametrizacionCifradoArchivosBancos parametrizacionCifradoArchivosBancos) {

        CifradoDeArchivos newInstance = null;
        try {           
                // Se realiza la introspección
                Class<?> clazz = Class
                        .forName(parametrizacionCifradoArchivosBancos
                                .getClaseImplementacion());
                Constructor<?> clazzConstructor = clazz.getConstructor();
                newInstance = (CifradoDeArchivos) clazzConstructor
                        .newInstance();

        } catch (NoClassDefFoundError e) {
            logger.info(e.getMessage());
        } 
        return newInstance;
    }
Allanh
  • 465
  • 1
  • 7
  • 19
  • I'm not sure why we would be interested in that particular piece of code. SMIME is about mail extensions. If you want to encrypt a file you look for the Cryptographic Message Syntax or PKCS#7 functionality. If the file is encrypted and embedded in a new structure we also call that "enveloped data". – Maarten Bodewes Aug 20 '19 at 21:55

1 Answers1

3

You can use cms provided by bouncycastle to encrypt file, provided that you have public keys. Smime gears more towards email.

Snippet as below:

CMSEnvelopedDataGenerator enGen = new CMSEnvelopedDataGenerator();

    for (Certificate c : certs) {
        enGen.addRecipientInfoGenerator(
                new JceKeyTransRecipientInfoGenerator((X509Certificate) c));
    }
    OutputEncryptor encryptor =
            new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC).setProvider("BC").build();
    CMSEnvelopedData envelopedData = enGen.generate(new CMSProcessableByteArray(bos.toByteArray()),
            encryptor);

Then the encrypted data will be:

envelopedData.getEncoded()
kabayaba
  • 195
  • 1
  • 13