Reputation: 11
I'm struggling with encrypting a username and password using CryptoJS and decrypting it on a remote CFC on my Coldfusion/Railo server. The error message I receive is: Given final block not properly padded. I have seen related topics but I can't 'translate' the solution to my case.
Here is the JavaScript that calls the function on the server:
var username = "[email protected]"
var password = "12345"
var ident = username.concat('|',password)
var key = CryptoJS.enc.Utf8.parse("dotterbloem20151");
var key = CryptoJS.enc.Base64.stringify(key);
var encrypted = CryptoJS.AES.encrypt(ident, key, {iv: key});
//In my JS the encryption/decryption works fine
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: key});
document.write(decrypted.toString(CryptoJS.enc.Utf8));
document.write('<BR>')
document.write(decrypted.toString(key));
var url = "cfc/roland.cfc?method=checkLoginstatus";
$.ajax({
url: url,
type: 'POST',
dataType: "json",
data: { "webkey" : encrypted.toString() },
success: function(response) {
}
});
And here is the function in my CFC:
<cffunction name="checkLoginstatus" access="remote" returntype="any" returnformat="plain">
<cfargument name="webkey" />
<cfoutput>
<cfset myKey = Tobase64("dotterbloem20151") />
<cfset myIV = charsetDecode("dotterbloem20151", "utf-8" )>
#Decrypt(ARGUMENTS.webkey, myKey, "AES/CBC/PKCS5Padding", "base64", myIV)#
</cfoutput>
</cffunction>
Upvotes: 1
Views: 436
Reputation: 61952
I don't know Coldfusion, but it looks like you're using the same password to derive a key and IV from it, but each of them differently.
You can do this in CryptoJS:
var iv = CryptoJS.enc.Utf8.parse("dotterbloem20151");
var key = CryptoJS.enc.Base64.stringify(iv);
var encrypted = CryptoJS.AES.encrypt(ident, key, {iv: iv});
This is a strange way to derive a key, because the 16 character password is encoded to Base 64 resulting in 24 encoded characters. 16 bytes and 24 bytes are both valid key sizes for AES, but using Base 64 to derive a key is at the very least strange.
This code is not very secure. If you have passwords, then you need to derive the key from that password in a secure fashion. You would need to utilize PBKDF2 with a random salt and many iterations. See How to securely hash passwords?
The IV also has to be randomly generated. It doesn't have to be secret, so you can simply send it along with the ciphertext.
Upvotes: 2