Jonas
Jonas

Reputation: 860

jasypt: Force same result when encrypting

I am just wondering whether it's possible to force an encryptor to always return the same encrypted value for the same input.

StandardPBEStringEncryptorencryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("My password");
encryptor.setAlgorithm("PBEWithMD5AndTripleDES");

String value1 = encryptor.encrypt("encryptme")
String value2 = encryptor.encrypt("encryptme")
String value3 = encryptor.encrypt("encryptSomethingElse")

assertEquals(value1,value2);
assertNotEquals(value1,value3);

Upvotes: 1

Views: 1048

Answers (1)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

As the documentation of StandardPBEStringEncryptor mentions,

If a random salt generator is used, two encryption results for the same message will always be different (except in the case of random salt coincidence).

And a random salt generator is indeed the default if you don't explicitly set a salt generator.

For the purpose of a unit test, you could set a salt generator that returns the same salt for the same input (or always returns the same salt), like ZeroSaltGenerator, using encryptor.setSaltGenerator(mySaltGenerator);

However make sure that this doesn't seep into your real code - only do that for testing.

Upvotes: 1

Related Questions