openssl命令列Base64編解碼

來源:互聯網
上載者:User

標籤:

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($source);?>

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

openssl命令列Base64編解碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.