简体   繁体   中英

PHP aes encryption

I'm quite new with PHP, i'm trying to make aes encryption on mp3 files, using IV from java and key from keystore, i recived key and iv in string form using BASE64 // System.out.println(DatatypeConverter.printBase64Binary(IV)); IV is here byte array. Here is part of my php code which shoudl encrypt file

$handle = fopen($file, "r");
$contents = fread($handle, filesize($file));
fclose($handle);



$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CTR, '');

$key = 'K/JED6M3WiSwke2ZZHvDInbRkUCI5lLk292ti9Bazmw=';
$iv =  'AAAAAQQFBgcAAAAAAAAAAQ==';


// Encrypt
if (mcrypt_generic_init($cipher, $key, $iv) != -1)
{
    $encrypted = mcrypt_generic($cipher, $contents);
    mcrypt_generic_deinit($cipher);
    $info = pathinfo($file);
 $nowa = $info['dirname'] 
        . DIRECTORY_SEPARATOR 
        . $info['filename'] 
        . '.' 
        . "mp3enc";
        echo $nowa;
        file_put_contents($nowa,$encrypted);
 }

But encryption does not works, new file is not being created. anyway i dont see what im doing wrong, so if anyone has any suggestion i woudl be greatful for them

Your key and iv seem to be base64encoded. Try decoding them before passing them to mcrypt_generic_init.

$key = base64_decode('K/JED6M3WiSwke2ZZHvDInbRkUCI5lLk292ti9Bazmw=');
$iv =  base64_decode('AAAAAQQFBgcAAAAAAAAAAQ==');

Also note, your binary .mp3 data will be padded with NULL characters so that it fits in the cipher and unless you handle this (which you are not doing) your decryption can never be binary safe. So rather than reinventing the wheel, I suggest using this PHP File encryption library .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM