problem with encryption
David Beck
david_beck at ministerschedulerpro.com
Mon Jun 4 17:19:56 EDT 2007
I finally resolved the issue with PHP and Rev encryption and I wanted to
share the resolution with the list. I was able to get aes-128 bit
working - 256 is still a mystery. (I think there is a problem with Rev
only looking at the first 16 bytes of the IV value for 256 bit, as it
appears bytes after #16 do not affect the resulting encrypted value with
Rev. I will log this as a bug.)
The problem is that when the data being encrypted was not 16-byte
aligned, meaning that the length of the data was not evenly divisible by
16, the Rev and PHP mcrypt libraries would encrypt and dycrypt the
values differently. I don't know if this is a bug in the mcrypt library
or in Rev or a general lack of specification but that was the problem.
Also PHP throws in some extra null characters when decrypting even
16-byte aligned strings at the end, so what I am doing is including the
length of the original data so that after the decryption is done with
PHP just that data is used as the final decrypted string.
So to put all of this is technical terms, here is the Rev script to
encrypt the data:
On encryptData theKey, @data
-- first generate a random 16 byte IV value
put getRandomSalt() into theIV
put binaryEncode( "N", the number of chars in data ) into dataSize
-- pad to size 16
repeat while the number of chars in data mod 16 is not 0
put numToChar( 0 ) after data
end repeat
encrypt data using "aes-128-cbc" with key theKey and iv theIV
if the result is not empty then
ci_NoteAlert "Error while encrypting:" && the result
exit to top
end if
put dataSize & theIV & it into data
return data
end encryptData
and the php to decode a chunk of data returned by the above script looks
like:
function decryptData( $theKey, &$data )
{
$dataLen = substr( $data, 0, 4 );
$dataLenArr = unpack( "N*", $dataLen );
$dataLen = $dataLenArr[1];
$data = substr( $data, 4 );
$iv = substr( $data, 0, 16 );
$data = substr( $data, 16 );
$td = mcrypt_module_open( MCRYPT_RIJNDAEL_128, '', 'cbc', '' );
mcrypt_generic_init( $td, $theKey, $iv );
$data = mdecrypt_generic( $td, $data );
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$data = substr( $data, 0, $dataLen );
}
Hope this is helpful to somebody in the future!
David
More information about the use-livecode
mailing list