openssl對base64編解碼的規範支持較差,用它編解碼的結果別的語言如php處理很不方便,注意的幾點整理以下php
1,若是php加密結果作base64編碼長度小於64,則須要添加一個換行符openssl才能解碼;編碼
2,php須要對base64編碼結果每隔64個字符插入一個換行符,openssl才能解碼。(緣由是openssl默認bufsize緩衝區大小16k,可是一旦涉及base64的計算緩衝區只有80字節,一旦編碼結果超過80字節則會計算失敗,base64編解碼沒法更改緩衝區大小)加密
示例代碼以下:spa
一,php加密openssl解密code
<?php function strtohex($x) { $s=''; foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c)); return($s); } $source = file_get_contents("phpencrypt.plain"); $iv = "1234567812345678"; $pass = 'a12ssdamqweret09'; $method = 'aes-128-cbc'; $content = base64_encode(openssl_encrypt($source, $method, $pass, true, $iv)); $newcontent = ""; for($i = 0, $len = strlen($content); $i < $len; $i += 64){ $newcontent = $newcontent . substr($content, $i, 64); if($i + 64 < $len){ $newcontent .= "\n"; } if($len < 64){ $newcontent .= "\n"; } } file_put_contents ('./phpencrypt.encrypted',$newcontent); $exec = "openssl enc -".$method." -d -a -bufsize 1 -in phpencrypt.encrypted -out phpencrypt.plain2 -nosalt -nopad -K ".strtohex($pass)." -iv ".strtohex($iv); echo $exec."\n"; exec($exec); $source = file_get_contents("phpencrypt.plain2"); echo trim(trim($source),"^F"); ?>
二,openssl加密php解密blog
<?php function strtohex($x) { $s=''; foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c)); return($s); } $iv = "1234567812345678"; $pass = 'a12ssdamqweret09'; $method = 'aes-128-cbc'; echo "openssl enc -aes-128-cbc -a -in phpdecrypt.plain -out phpdecrypt.encrypted -K ".strtohex($pass)." -iv ".strtohex($iv)."\n"; echo exec("openssl enc -aes-128-cbc -a -in phpdecrypt.plain -out phpdecrypt.encrypted -K ".strtohex($pass)." -iv ".strtohex($iv)); $content = file_get_contents('./phpdecrypt.encrypted'); $data = openssl_decrypt(base64_decode($content), $method, $pass, true, $iv); echo trim($data); ?>