openssl Rsa 分段加密解密

 密钥长度 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;
}

 

posted @ 2016-09-21 13:39  程序员大叔  阅读(3763)  评论(1编辑  收藏  举报