14

Can anyone show me (or provide a link to) an example of how to encrypt a file in Java using bouncy castle? I've looked over bouncycastle.org but cannot find any documentation of their API. Even just knowing which classes to use would be a big help for me to get started!

Lee Warner
  • 2,543
  • 4
  • 30
  • 45
  • Go with cb160's links, and also be sure to get the source code for bouncycastle. The API documentation is mostly poor and often very poor. However, the source code is quite readable and I often used it to answer questions like "what kind of CipherParameters does the RijndaelEngine need?". Just look at the relevant Rijndael method and it will be obvious. – President James K. Polk Jan 12 '10 at 23:22
  • @JamesReinstateMonicaPolk: what is cb160's link ? I don't find it. – Hoang Nov 11 '19 at 02:50
  • 1
    @Hoang: Let me time-travel back 10 years ago and see what I meant. But if I get stuck in the past it's your fault. – President James K. Polk Nov 11 '19 at 04:25

5 Answers5

20

What type of encryption do you want to perform? Password-based (PBE), symmetric, asymmetric? Its all in how you configure the Cipher.

You shouldn't have to use any BouncyCastle specific APIs, just the algorithms it provides. Here is an example that uses the BouncyCastle PBE cipher to encrypt a String:

import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class PBE {

    private static final String salt = "A long, but constant phrase that will be used each time as the salt.";
    private static final int iterations = 2000;
    private static final int keyLength = 256;
    private static final SecureRandom random = new SecureRandom();

    public static void main(String [] args) throws Exception {
        Security.insertProviderAt(new BouncyCastleProvider(), 1);

        String passphrase = "The quick brown fox jumped over the lazy brown dog";
        String plaintext = "hello world";
        byte [] ciphertext = encrypt(passphrase, plaintext);
        String recoveredPlaintext = decrypt(passphrase, ciphertext);

        System.out.println(recoveredPlaintext);
    }

    private static byte [] encrypt(String passphrase, String plaintext) throws Exception {
        SecretKey key = generateKey(passphrase);

        Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
        cipher.init(Cipher.ENCRYPT_MODE, key, generateIV(cipher), random);
        return cipher.doFinal(plaintext.getBytes());
    }

    private static String decrypt(String passphrase, byte [] ciphertext) throws Exception {
        SecretKey key = generateKey(passphrase);

        Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
        cipher.init(Cipher.DECRYPT_MODE, key, generateIV(cipher), random);
        return new String(cipher.doFinal(ciphertext));
    }

    private static SecretKey generateKey(String passphrase) throws Exception {
        PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWITHSHA256AND256BITAES-CBC-BC");
        return keyFactory.generateSecret(keySpec);
    }

    private static IvParameterSpec generateIV(Cipher cipher) throws Exception {
        byte [] ivBytes = new byte[cipher.getBlockSize()];
        random.nextBytes(ivBytes);
        return new IvParameterSpec(ivBytes);
    }

}
Kevin
  • 30,111
  • 9
  • 76
  • 83
  • 2
    If you are getting java.security.InvalidKeyException: Illegal key size ref: http://stackoverflow.com/a/6481658/234110 – Anand Rockzz Jun 25 '15 at 06:01
  • @Kevin When I used this example, the plain text recovered after decrypting the cipher text is completely different than the original plain text – Vinayaka S P Jun 14 '22 at 14:49
3

You can view the java doc at http://bouncycastle.org/docs/docs1.6/index.html

You can download examples from this page: http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0764596330,descCd-DOWNLOAD.html

Robert Christie
  • 20,177
  • 8
  • 42
  • 37
2

If you don't have any particular reason for using BouncyCastle, you can find a good tutorial and background information on the Java built-in cryptography support with several code examples here.

Vukašin Manojlović
  • 3,717
  • 3
  • 19
  • 31
jarnbjo
  • 33,923
  • 7
  • 70
  • 94
  • 1
    It is worth pointing out that BouncyCastle is just a "provider" that works within the built-in cryptography framework (JCE). It's frequently used because it contains a more complete suite of primitives than the default provider. – caf Jan 13 '10 at 04:02
  • 1
    BouncyCastle is not "just a provider". You can also use the cryptography functionality of BouncyCastle through their proprietary API. You are right that BouncyCastle provide additional cryptographic algorithms, but I've rarely seen any real need for these. More than often however, BouncyCastle is used for functionality already provided by the standard API and VM embedded security providers. – jarnbjo Jan 13 '10 at 12:14
1

The best place to find Bouncy Castle java code examples is to go through the test cases in the test suite of bouncy castle Bouncy Castle latest release java

These test suites contain non-deprecated code which can be used readily

Saurabh
  • 195
  • 1
  • 2
  • 7
0

While it's an indirect answer to your question, perhaps you'll find it useful to use jasypt to handle the encryption.

here's an example of how to encrypt a file using jasypt: http://www.jasypt.org/encrypting-configuration.html

And, here's how to configure bouncy castle as a provider for jasypt: http://www.jasypt.org/bouncy-castle.html

Edward Q. Bridges
  • 16,712
  • 8
  • 35
  • 42
  • 1
    A second 3rd party library to abstract the first probably unrequired 3rd party library? Sounds like a very good idea. – jarnbjo Jan 12 '10 at 20:55
  • We are using jasypt and BouncyCastle. Jasypt handles the transparent encryption and decryption of database columns with Hibernate, and BouncyCastle does the actual encryption and decryption. – Omniwombat Jan 12 '10 at 21:46