zoukankan      html  css  js  c++  java
  • php7实现基于openssl的加密解密方法

    还需要注意的是加密字符串长度问题,如果加密字符串长度太长需要进行分段加解密,如下代码:

    加密:(公匙加密,私密一般用来解密)

    function encrypt($originalData){
        $publicKeyFilePath = '/www/ceshi/rsa_public_key.pem';
        extension_loaded('openssl') or die('php需要openssl扩展支持');
        file_exists($publicKeyFilePath) or die('公钥的文件路径不正确');
        $publicKey = openssl_pkey_get_public(file_get_contents($publicKeyFilePath));
        $publicKey or die('公钥不可用');
        $crypto = '';
        foreach (str_split($originalData, 117) as $chunk) {
            $encryptData = '';
            if(openssl_public_encrypt($chunk, $encryptData, $publicKey)){
                $crypto .= $encryptData;
            }else{
                die('加密失败');
            }
        }
        return base64_encode($crypto);
    }

    解密:

    function decrypt($encryptData){
        $privateKeyFilePath = '/www/ceshi/rsa_private_key.pem';
        extension_loaded('openssl') or die('php需要openssl扩展支持');
        file_exists($privateKeyFilePath) or die('密钥的文件路径不正确');
        $privateKey = openssl_pkey_get_private(file_get_contents($privateKeyFilePath));
        $privateKey or die('密钥不可用');
        $decryptData = '';
        $crypto = '';
        foreach (str_split(base64_decode($encryptData), 128) as $chunk) {
            if(openssl_private_decrypt($chunk, $decryptData, $privateKey)){
                $crypto .= $decryptData;
            }else{
                die('解密失败');
            }
    
        }
        return $crypto;
    }

    调用:

    $aa = encrypt('aa');
    $bb = decrypt($aa);
    var_dump($bb);
    输出的结果为:aa
  • 相关阅读:
    模块移植-加宏选择性编译
    模块-各个模块的路径所在
    ubuntu-系统卡慢解决(转载)
    meld文件的脚本
    artTemplate模板引擎
    前端完全分离和前端不完全分离
    px em rem的区别
    原型和原型链
    阻止默认事件
    document.ready和onload的区别
  • 原文地址:https://www.cnblogs.com/herry52/p/7544898.html
Copyright © 2011-2022 走看看