Using Jasypt with the Bouncy Castle JCE provider

The Bouncy Castle is a powerful and complete cryptography package which includes, among other things, a JCE provider implementing much more encryption and digest algorithms than the standard Java Virtual Machine's provider.

Among others, Bouncy Castle implements the AES (Advanced Encryption Standard) [wikipedia] algorithms.

Bouncy Castle can be used in jasypt in a very easy way, just like with any other JCE provider. For this, we should know:

  • The provider class (implementation of java.security.Provider) is org.bouncycastle.jce.provider.BouncyCastleProvider
  • The name of the Bouncy Castle provider, once registered, is "BC".

Now we can use Bouncy Castle at jasypt both registering the provider beforehand (thus using its name, BC) or not registering it (and using its provider class):

...
StandardPBEStringEncryptor myFirstEncryptor = new StandardPBEStringEncryptor();
myFirstEncryptor.setProvider(new BouncyCastleProvider());
myFirstEncryptor.setAlgorithm("PBEWITHSHA256AND128BITAES-CBC-BC");
myFirstEncryptor.setPassword(myPassword);

String myFirstEncryptedText = myFirstEncryptor.encrypt(myText);
...

...or, by provider name...

...
Security.addProvider(new BouncyCastleProvider());
...
StandardPBEStringEncryptor mySecondEncryptor = new StandardPBEStringEncryptor();
mySecondEncryptor.setProviderName("BC");
mySecondEncryptor.setAlgorithm("PBEWITHSHA256AND128BITAES-CBC-BC");
mySecondEncryptor.setPassword(myPassword);

String mySecondEncryptedText = mySecondEncryptor.encrypt(myText);
...

We can also use it for digests...

...        
StandardStringDigester digester = new StandardStringDigester();
digester.setProvider(new BouncyCastleProvider());
digester.setAlgorithm("WHIRLPOOL");

String digest = digester.digest(message);
...

...we can also use password-specific utils like ConfigurablePasswordEncryptor...

...        
ConfigurablePasswordEncryptor passwordEncryptor = new ConfigurablePasswordEncryptor();
passwordEncryptor.setProvider(new BouncyCastleProvider());
passwordEncryptor.setAlgorithm("WHIRLPOOL");

String encryptedPassword = passwordEncryptor.encryptPassword(password);
...

And also, we can use it in Hibernate mappings, when configuring the typedefs by extension, like:

  <hibernate-mapping package="myapp">
    ...
    <typedef name="encryptedString" class="org.jasypt.hibernate4.type.EncryptedStringType">
      <param name="algorithm">PBEWITHSHA256AND128BITAES-CBC-BC</param>
      <param name="providerName">BC</param>
      <param name="password">jasypt</param>
      <param name="keyObtentionIterations">1000</param>
    </typedef>
    ...
    <class name="UserData" table="USER_DATA">
      ...
      <property name="address" column="ADDRESS" type="encryptedString" />
      ...
    <class>
    ...
  <hibernate-mapping>