处理caid启发的php-rsa

2021/02/02 posted in  测试
Tags: 

一直觉得rsa无非就是私钥加解密,公钥加解密。
过长的字符串公钥加解密是要做处理的

加密

public function EncryptData($source)
{
    $pub_key_string = '-----BEGIN PUBLIC KEY-----
xx省略
-----END PUBLIC KEY-----';
    $t = openssl_get_publickey($pub_key_string);
    $crypttext = '';
    foreach (str_split($source, 117) as $chunk) {
        openssl_public_encrypt($chunk, $encryptData, $t);
        $crypttext .= $encryptData;
    }
    return(base64_encode($crypttext));
}

按117长度划分加密

解密

public function decrypt($encryptData){

        $pub_key_string = '-----BEGIN PUBLIC KEY-----
省略php-pcks公钥
-----END PUBLIC KEY-----';
$t = openssl_pkey_get_public($pub_key_string);
        $crypttext = '';
        $source = base64_decode($encryptData);
        foreach (str_split($source, 128) as $chunk) {
            openssl_public_decrypt($chunk, $dd, $pub_key_string);
            $crypttext .= $dd;
        }
        return trim($crypttext);
    }

按128长度划分解密

caid示例

$json = [
    'bootTimeInSec' => '1595643553',
    'countryCode' => 'CN',
    'language' => 'zh-Hans-CN',
    'deviceName' => 'e910dddb2748c36b47fcde5dd720eec1',
    'systemVersion' => '14.0',
    'machine' => 'iPhone10,3',
    'carrierInfo' => '中国移动',
    'memory' => '3955589120',
    'disk' => '63900340224',
    'sysFileTime' => '1595214620.383940',
    'model' => 'D22AP',
    'timeZone' => '28800',
];
$json = json_encode($json,JSON_UNESCAPED_UNICODE);
$result = $this->EncryptData($json);
$param = [
    'dev_id' => '省略dev_id配置',
    'encrypted_device_info' => $result
];
// caid测试地址
$url = "https://caid.china-caa.org/test/v1.0/get";
$result = http::postjson($url,$param);

总结

值得注意的是,如果选择密钥是1024bit长的(openssl genrsa -out rsa_private_key.pem 1024),那么支持加密的明文长度字节最多只能是1024/8=128byte;
如果加密的padding填充方式选择的是OPENSSL_PKCS1_PADDING(这个要占用11个字节),那么明文长度最多只能就是128-11=117字节。如果超出,那么这些openssl加解密函数会返回false。
这时有个解决办法,把需要加密的源字符串按少于117个长度分开为几组,在解密的时候以172个字节分为几组。

参考链接

https://blog.csdn.net/leedaning/article/details/51780511