Reputation: 14694
I have CryptoJS running and I need to do the following:
I have a username and a password. U encrypt the username with the password:
var encrypted = CryptoJS.AES.encrypt("user", "pass");
How can I create a String out of this object to store it in my LocalStorage
?
At the end I need to load it from my LocalStorage
and compare it to:
var encrypted2 = CryptoJS.AES.encrypt("user", "pass");
if encrypted === encrypted2
all is fine.
But I can't get out a string of encrypted
it's an CryptoJS.AES Object
and when I use JSON.stringify
I get the error: TypeError: Converting circular structure to JSON
Upvotes: 4
Views: 3614
Reputation: 61952
encrypted2.toString()
will get you the OpenSSL formatted representation of the ciphertext. Note that it can't produce the same result, because you're using the password based encryption, during which a random salt is generated to produce the actual key and IV for the encryption. Every ciphertext that you produce with the same parameters will look differently.
Only the decryption of a ciphertext can get you the information whether the key+IV or password+salt were correct and then only when you have some kind of integrity check included (Padding is a poor-mans integrity check). See also: Should we MAC-then-encrypt or encrypt-then-MAC?
If you only want to check whether a username is the same, you should use the same techniques as used for passwords. That is, you should use hashing. CryptoJS provides multiple hash functions including an implementation of PBKDF2 for extra security. This will give you the property that you want when you set the password as the salt for PBKDF2.
Upvotes: 3