Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encryption function returns different output every time

I have following code -

import org.jasypt.util.text.BasicTextEncryptor;

public static void main(String[] args) {
    BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
    textEncryptor.setPassword("kshitiz");

    String cipherText = textEncryptor.encrypt("my_secret");
    System.out.println(cipherText);
}

Every time I run it the output is different -

1st run - 7vZzcsVFortOUf4yLyQ9xSEUM2pKSXAs

2nd run - Z3YDxfPpubGAQMpr+5MAKR5P09mAJ7Wd

3rd run - kVGIGcCEXZDFJnV/n0lxyFN5WW7dWMT7

All the outputs are correct as decrypting them gives me my_secret.

How is this so?

like image 979
Kshitiz Sharma Avatar asked Aug 08 '13 04:08

Kshitiz Sharma


2 Answers

Copied from documentation of the method.

The mechanisms applied to perform the encryption operation are described in PKCS #5: Password-Based Cryptography Standard.

This encryptor uses a salt for each encryption operation. The size of the salt depends on the algorithm being used. This salt is used for creating the encryption key and, if generated by a random generator, it is also appended unencrypted at the beginning of the results so that a decryption operation can be performed.

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). This may enforce security by difficulting brute force attacks on sets of data at a time and forcing attackers to perform a brute force attack on each separate piece of encrypted data.

Essentially, to comply to the standard, a cryptographic salt which is randomly generated at runtime is used and appended to the output string. This salt prevents brute force attacks using pre-computed rainbow tables.

like image 194
initramfs Avatar answered Oct 21 '22 16:10

initramfs


It is probably using random IVs or random padding. This is actually important for security under some attacks but it will result in different ciphertexts for the same message.

like image 41
Antimony Avatar answered Oct 21 '22 15:10

Antimony