Here is an encryption solution for those of you who might need to implement AES-128 encryption between a LiveCode app and a PHP script. I read the following thread (http://forums.livecode.com/viewtopic.ph ... pt#p107448) and found a way to successfully pass an encrypted string from LiveCode to a PHP script for decryption (thanks dcpbarrington!), but I was unable to send encrypted data from a PHP script back to LiveCode for successful decryption. I suspected that the problem had to do with padding, and I was correct. Problem solved! The problem was with the block size and the length of the string to be encrypted.
See the PHP EncryptIt function below. The following code must be included accordingly:
Code: Select all
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $blockSize - (strlen($string) % $blockSize);
$string .= str_repeat(chr($padding), $padding);
I hope this information helps someone... Here are the sample functions: EncryptIt and DecryptIt for LiveCode, and EncryptIt and DecryptIt for PHP.
Cheers!
- Boo
Gulf Breeze, Florida
LiveCode Code -------------------------------
Code: Select all
function EncryptIt pTokenText
local tHex, tKeyHex
put "1234567891234567" into tKeyHex
put "9876543219876543" into tIVHex
encrypt pTokenText using "aes-128-cbc" with key tKeyHex and IV tIVHex at 128 bit
put it into tTokenValue
if the result is Empty then
return base64Encode( tTokenValue )
else
return "Error:" && the result
end if
end EncryptIt
function DecryptIt pTokenText
local tHex, tKeyHex
put base64decode(pTokenText) into pTokenText
put "1234567891234567" into tKeyHex
put "9876543219876543" into tIVHex
decrypt pTokenText using "aes-128-cbc" with key tKeyHex and IV tIVHex at 128 bit
put it into tTokenValue
if the result is Empty then
return tTokenValue
else
return "Error:" && the result
end if
end DecryptIt
PHP Code -----------------------------
Code: Select all
<?php
$string="LiveCode Rocks!";
$key="1234567891234567";
$iv="9876543219876543";
$encrypted= EncryptIt($string,$key,$iv);
echo $encrypted."<br>";
$decrypted= DecryptIt($encrypted,$key,$iv);
echo $decrypted;
function EncryptIt($string, $key, $iv){
// This fixes the padding issue so you can decrypt the encrypted string in LiveCode.
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $blockSize - (strlen($string) % $blockSize);
$string .= str_repeat(chr($padding), $padding);
// Hooray!
$string = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $iv);
$string = base64_encode($string);
return $string;
}
function DecryptIt($string, $key, $iv){
$string = base64_decode($string);
$string = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $iv);
return $string;
}
?>