openssl命令行Base64编解码

openssl对base64编解码的规范支持较差,用它编解码的结果别的语言如php处理很不方便,注意的几点整理如下

1,如果php加密结果做base64编码长度小于64,则需要添加一个换行符openssl才能解码;

2,php需要对base64编码结果每隔64个字符插入一个换行符,openssl才能解码。(原因是openssl默认bufsize缓冲区大小16k,但是一旦涉及base64的计算缓冲区只有80字节,一旦编码结果超过80字节则会计算失败,base64编解码无法更改缓冲区大小)

示例代码如下:

一,php加密openssl解密

<?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解密

<?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);

?>
posted @ 2015-08-10 22:48  ciaos  阅读(3828)  评论(0编辑  收藏  举报