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);
    
    ?>
  • 相关阅读:
    Xcode 10 关于 CocoaPods 安装失败的问题RuntimeError
    iOS 解决xcode设置全局断点后 执行视频播放时自动进入断点cxa_throw
    iOS swift String 换行显示
    iOS wkWebView点击链接无反应
    iOS swift跑马灯滚动可以点击
    iOS swift版本无限滚动轮播图
    iOS swift中比较模型数组是否相等
    iOS valueForKeyPath快速计算求和、平均值、最大、最小
    iOS 全屏播放网页视频退出后状态栏被隐藏
    vacabulary1
  • 原文地址:https://www.cnblogs.com/ciaos/p/4719556.html
Copyright © 2011-2022 走看看