zoukankan      html  css  js  c++  java
  • 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 .= "
    ";
                    }
                    if($len < 64){
                            $newcontent .= "
    ";
                    }
            }
            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."
    ";
            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)."
    ";
        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);
    
    ?>
  • 相关阅读:
    面向对象(Object Oriented)
    文件操作
    函数
    dict--字典
    list--列表
    Ubuntu_18.04安装网易云音乐
    初识数据类型
    css控制内容显示,自动加"..."
    css固定元素位置(fixed)
    解决IE下iframe默认有白色背景的bug
  • 原文地址:https://www.cnblogs.com/ciaos/p/4719556.html
Copyright © 2011-2022 走看看