Closed LogiMateenSA closed 3 years ago
That's normal, a random IV is used each time to ensure no two results are the same, which prevents attackers from essentially having a list of ciphertexts that they can use to get the plaintext value of an encrypted string by comparing the results. The .toString() method also concatenates the ciphertext with a salt that is different each time.
Thats sounds like a cool feature. Thanks for letting me know.
How to compare a plain value with an encrypted hash? I'm aes encrypting the email and need to compare the plain email with the hash to authenticate the user.
@pavinduLakshan There's a few things you'd need to consider there:
1) Normally you wouldn't just use an email to authenticate a user, as email addresses generally aren't kept private, so on such a system anyone who knows someone else's email could pretend to be them, or they could just enter a random email and hope it works (and in this case, common names and such would probably work).
2) If the goal is to authenticate users, and emails are supposed to be kept a secret, you would want to hash it using "bcrypt" for example instead of encrypting it with AES. The goal of hashing is to produce an output that cannot be reversed, whereas encryption is intended to be reversed. So it doesn't make sense to encrypt data that you only want to compare rather than actually read the value of. Encrypting something also produces a key, which you'd need to keep safe somehow, and in 99% of cases, those keys should not be held by the service provider at all to protect from data breaches or the service itself abusing its power.
3) You'd have to encrypt the email using the AES.encrypt()
function, but instead of turning it into a string, get the iv
from it. You can imagine the IV as similar to a salt. The reason why each time you encrypt some plaintext, the ciphertext output is different is because of that IV. So in order to compare plaintext with some ciphertext, it needs to be encrypted using the same IV so that the result is the same. So you'd get the IV from the output of AES.encrypt()
, and store it alongside the ciphertext. Then, you could use that IV each time you want to compare an email.
Overall, I'd recommend using passwords in combination with emails, as emails alone are nowhere near secure enough (no single piece of data is unless it's long and random enough to truly be unique). From there, I'd recommend hashing the passwords, and if you want to, encrypt the email using the user's password, and decrypt it when they log in and store it on the client-side. This should protect you against data breaches, invasions of privacy etc.