Reputation: 337
I am trying to encrypt a string when setting it as a cookie with javascript AES, it encrypts fine. but after I recuperate the string (within the cookie) to decrypt it, it doesn't come back as the original string.
class Auth{
constructor(){
this.pass = "iscae";
this.cookies = new Cookies();
this.email = this.cookies.get("email");
this.connected = false;
this.checkConnection();
return this;
}
checkConnection(){
if(this.email !== undefined){
this.email = crypto.AES.decrypt(this.email,this.pass).toString();
this.connected = true;
}
else{
this.connected = false;
}
return {
email : this.email,
connected : this.connected
};
}
connect(email){
this.email = crypto.AES.encrypt(email,this.pass).toString();
this.cookies.set("email",this.email);
return this;
}
disconnect(){
this.cookies.remove("email");
return this;
}
}
export default Auth;
Upvotes: 3
Views: 8272
Reputation: 22515
The problem is in the line:
this.email = crypto.AES.decrypt(email,this.pass).toString();
Without a parameter in toString()
you'll get a string of hexadecimal ASCII codes.
For example, when the plain text is "[email protected]", you'll get:
7465737440656d61696c2e636f6d
in hexadecimal representation (74="t", 65="e",...).
To get the normal string representation, i.e.
you need to pass a parameter like this:
toString(CryptoJS.enc.Utf8);
toString
behaves like this because the decryption function crypto.AES.decrypt()
returns a byte array, as the content could be binary data as well (e.g. pictures or other data). toString()
just converts each byte into it's hexadecimal string reprensentation.
By passing the parameter CryptoJS.enc.Utf8
you tell the toString()
method explicitely to treat the bytes as UTF-8 encoded characters.
Upvotes: 6