I have an encrypted email id which I am storing in the database.
The next time the same email id comes in, I wanted to encrypt it and query the db whether the same exists. As I have come to know, the randomness of the AES is one of the key aspects of it being secure therefore, this approach is not possible. I should not set the IV to repeat the pattern.
What is a more suitable approach to take here in this case? Other than getting all the ids and doing a client side decrypt and match?
Any pointers appreciated.
As long as you use the same Key and the same IV (initialisation vector), you'll get the same result, e.g.
const crypto = require('crypto');
function encrypt(plainText, keyBase64, ivBase64) {
var key = Buffer.from(keyBase64, 'base64');
var iv = Buffer.from(ivBase64, 'base64');
/* Using 128 Bit AES with CBS. */
var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
cipher.update(plainText, 'utf8', 'base64')
return cipher.final('base64');
};
var keyBase64 = "sTEhO2zJ8f2Lck59VppiCQ==";
var ivBase64 = 'Xpu5CSY5hz0PeDnNF0TM4A==';
var plainText = 'Sample email text';
console.log('Plaintext: ', plainText);
var cipherText = encrypt(plainText, keyBase64, ivBase64);
console.log('Ciphertext: ', cipherText);
var cipherText2 = encrypt(plainText, keyBase64, ivBase64);
console.log('Ciphertext 2: ', cipherText2);
You could also consider hashing the email and saving the hash, e.g.
var sha256 = crypto.createHash('sha256').update(plainText).digest("hex");
console.log('SHA256: ', sha256);
The hash will be stable for a given email body.