openssl Rsa 分段加密解密

时间:2021-11-17 18:31:15

 密钥长度 1024

openssl genrsa -out rsa_private_key.pem 1024
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

 

function readPublicKey($keyPath)
{
    $key = file_get_contents($keyPath);
    $this->rsaPublicKey =  openssl_pkey_get_public($key)
}
function readPrivateKey($keyPath)
{
    $key = file_get_contents($keyPath);
    $this->rsaPrivateKey =  openssl_pkey_get_private($key)
}
// 加密后转为base64编码
function encrypt($originalData)
{
    $crypto = '';
    foreach (str_split($originalData, 117) as $chunk)
    {
        openssl_public_encrypt($chunk, $encryptData, $this->rsaPublicKey);
        $crypto .= $encryptData;
    }
    return base64_encode($crypto);
}
// base64 post 过来后 '+' 号变成 空格
function decrypt($encryptData)
{
    $crypto = '';
    foreach (str_split(str_replace(' ', '+', base64_decode($encryptData)), 128) as $chunk)
    {
        openssl_private_decrypt($chunk, $decryptData, $this->rsaPrivateKey);
        $crypto .= $decryptData;
    }
    return $crypto;
}