项目中需要加密超长json内容才发现rsa加密长度有限制,于是换一种思路:我们将原本需要加密的内容拆分为多个字符串,一段一段的加密,解密端也是一段一段的解密即可完成。

(1).确认每次加密多少长度

首先我们要知道rsa加密长度是多少,1024位的rsa能加密的长度也是1024位。那么我们一次加密多长的字符串比较好? 是不是1024/8呢?不是的!因为如果你每次能保证每次要加密的是1024位那就没事这样算是对,但是如果你要加密的字符串不足1024位,不足的部分会用你设置的padding方式去填充这部分内容。那么我们分段加密的长度的公式就是:证书位数/8-padding长度,例如1024的证书配合OPENSSL_PKCS1_PADDING 长度的公式:1024/8-11即可

(2).确认每次解密多少长度

解密不需要考虑填充,所以每次解密大小 = 证书位数/8

(3).我们封装了一个简单的类你可以直接使用,同事(刘平)编写,我整理完善了下。

string.
     * privateKey => string.
     *
     * @var mixed
     */
    protected $config;
    /**
     * 初始化.
     *
     * @param array $config
     */
    public function __construct($config)
    {
        $this->config = $config;
    }
    /**
     * 获取密钥分段加密长度.
     *
     * @param Closure $keyClosure
     *
     * @return int
     *
     * @throws Exception
     */
    protected function getEncryptBlockLen($keyClosure)
    {
        $key_info = openssl_pkey_get_details($keyClosure);
        if (!$key_info)
        {
            throw new Exception('获取密钥信息失败' . openssl_error_string());
        }
        // bits数除以8 减去padding长度,OPENSSL_PKCS1_PADDING 长度是11
        // php openssl 默认填充方式是 OPENSSL_PKCS1_PADDING
        return $key_info['bits'] / 8 - 11;
    }
    /**
     * 获取密钥分段解密长度.
     *
     * @param Closure $keyClosure
     *
     * @return int
     *
     * @throws Exception
     */
    protected function getDecryptBlockLen($keyClosure)
    {
        $key_info = openssl_pkey_get_details($keyClosure);
        if (!$key_info)
        {
            throw new Exception('获取密钥信息失败' . openssl_error_string());
        }
        // bits数除以8得到字符长度
        return $key_info['bits'] / 8;
    }
    /**
     * 数据加密.
     *
     * @param string $text 需要加密的文本
     * @param int $type 加密方式:1.公钥加密 2.私钥加密
     *
     * @return string
     *
     * @throws Exception
     */
    public function encrypt($text, $type)
    {
        //获取密钥资源
        $keyClosure = 1 == $type ? openssl_pkey_get_public($this->config['publicKey']) : openssl_pkey_get_private($this->config['privateKey']);
        if (!$keyClosure)
        {
            throw new Exception('获取密钥失败,请检查密钥是否合法');
        }
        //RSA进行加密
        $encrypt = '';
        $plainData = str_split($text, $this->getEncryptBlockLen($keyClosure));
        foreach ($plainData as $key => $encrypt_item)
        {
            $isEncrypted = (1 == $type) ? openssl_public_encrypt($encrypt_item, $encrypted, $keyClosure) : openssl_private_encrypt($encrypt_item, $encrypted, $keyClosure);
            if (!$isEncrypted)
            {
                throw new Exception('加密数据失败,请检查密钥是否合法,' . openssl_error_string());
            }
            $encrypt .= $encrypted;
        }
        $encrypt = base64_encode($encrypt);
        //返回
        return $encrypt;
    }
    /**
     * 数据解密.
     *
     * @param string $text 需要加密的文本
     * @param int $type 加密方式:1.公钥加密 2.私钥加密
     *
     * @return string
     *
     * @throws Exception
     * @throws
     */
    public function decrypt($text, $type)
    {
        //获取密钥资源
        $keyClosure = 1 == $type ? openssl_pkey_get_public($this->config['publicKey']) : openssl_pkey_get_private($this->config['privateKey']);
        if (!$keyClosure)
        {
            throw new Exception('获取密钥失败,请检查密钥是否合法');
        }
        //RSA进行解密
        $data = base64_decode($text);
        $data = str_split($data, $this->getDecryptBlockLen($keyClosure));
        $decrypt = '';
        foreach ($data as $key => $chunk)
        {
            $isDecrypted = (1 == $type) ? openssl_public_decrypt($chunk, $encrypted, $keyClosure) : openssl_private_decrypt($chunk, $encrypted, $keyClosure);
            if (!$isDecrypted)
            {
                throw new Exception('解密数据失败,请检查密钥是否合法,' . openssl_error_string());
            }
            $decrypt .= $encrypted;
        }
        //返回
        return $decrypt;
    }
}
//01.配置公钥私钥
$config = [
    'publicKey' => '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAsst/VK6RA+4tFTJtHUTEUY4E
uN/NdXBUc3Lbb9/P+SqvpTI7NCyvl/bSCSXGOeURzIKGffSTe7oKbAITO5GAKbxS
dz8bj8/rb7r9QUwzdvjY6/9x0M3M295GCwrH5ROXv/dGGh4FKcnl31pHuTJmuz4D
HugXS8FNnxlnHwZNLwIDAQAB
-----END PUBLIC KEY-----',
    'privateKey' => '-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMCyy39UrpED7i0V
Mm0dRMRRjgS43811cFRzcttv38/5Kq+lMjs0LK+X9tIJJcY55RHMgoZ99JN7ugps
AhM7kYApvFJ3PxuPz+tvuv1BTDN2+Njr/3HQzczb3kYLCsflE5e/90YaHgUpyeXf
Wke5Mma7PgMe6BdLwU2fGWcfBk0vAgMBAAECgYANOPePwC7OUpe4TjkMlbKPSg1V
s53fykwv71AVUKLp8W4FaW998oGSdvn/xZLq/DQEuaTHN8Ndj2LfrjOiQDcmlrQS
5vaazxhTaBW4JuFEXltXnstf+mZhyu3bpm5Ta/yLQiZ8ROUPXMFEvANyg7WgOKCv
fY1olbhGpIMexRkMgQJBAOfrjA9fFUT31h7qFwZhJXKkAydPqZZFyxDhkSPNEkpA
dRqUn4AoTW3LdCHpy7ka+/zFLvPrPkwrd8AVZKZyX8ECQQDUtLuH1tC9xY2xTMI3
4JDpw1TSPEpgT2kng1zSLfL0Qj4aKCm9PFlqx8REksf9H4+7ZztOSb9846JAJXdx
eOjvAkAF1A6WCE6xiATyi/F+MIzPX73QjBj39NMQnoqWOr4d7ZbDzz5e6yRfAQDv
JUAAa+QvSwlOCfhr05/TzPXVlQRBAkEAs2CHFZNPDfrf9zloQH8dNkYH7hPyFS5i
23Oof4dIcDy86oocSP3v2mEFX175ULmhGMWB+g+vcL73QWlXRVZV+QJAXDPOLW2C
S9ot0TwcHuWFY4hZkc5E8dHV3v5Hip6b12dkeVqyzNZ1onftUV5VlqG5LnzyMcS9
TXlJaV2+SL97nQ==
-----END PRIVATE KEY-----',
];
//02.初始化
$openssl = new Openssl($config);
//03.私钥加密->公钥解密,加密5000长度的字符串A
$waitChar = str_repeat('A', 5000);
$privateEnData = $openssl->encrypt($waitChar, 2);  //私钥加密
$publicDeData = $openssl->decrypt($privateEnData, 1); //公钥解密
//04.公钥加密->私钥解密,加密10000长度的字符串B
$waitChar = str_repeat('B', 10000);
$publicEnData = $openssl->encrypt($waitChar, 1); //公钥加密
$privateDeData = $openssl->decrypt($publicEnData, 2); //私钥解密

 

版权声明:本文为fengzhishangcc原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/fengzhishangcc/p/16116142.html