PHP RSA公钥加密解密,私钥pfx加密解密

https://blog.csdn.net/lensko/article/details/100030675

使用公钥加密数据

function public_key_encrypt($str)
{
    $rsa_pub = file_get_contents(ROOT_PATH . 'data/rsa/public_key.pem');

    $encrypted = '';

    $pub_id = openssl_get_publickey($rsa_pub);
    $key_len = openssl_pkey_get_details($pub_id)['bits'];

    $part_len = $key_len / 8 - 11;

    $parts = str_split($str, $part_len);

    foreach ($parts as $part) {
        $encrypted_temp = '';
        openssl_public_encrypt($part, $encrypted_temp, $rsa_pub);
        $encrypted .= $encrypted_temp;
    }

    return base64_encode($encrypted);
}

使用私钥加密数据

function private_key_encrypt($str)
{
    $rsa_pri = file_get_contents(ROOT_PATH . 'data/rsa/private_key.pem');

    $encrypted = '';

    $pri_id = openssl_get_privatekey($rsa_pri);
    $key_len = openssl_pkey_get_details($pri_id)['bits'];

    $part_len = $key_len / 8 - 11;

    $parts = str_split($str, $part_len);

    foreach ($parts as $part) {
        $encrypted_temp = '';
        openssl_private_encrypt($part, $encrypted_temp, $rsa_pri);
        $encrypted .= $encrypted_temp;
    }

    return base64_encode($encrypted);
}

公钥解密

function public_key_decrypt($str)
{

    $rsa_pub = file_get_contents(ROOT_PATH . 'data/rsa/public_key.pem');


    $str = str_replace(' ', '+', $str);

//    openssl_private_decrypt(base64_decode($str), $data, $rsa_pr);

    $decrypted = "";

    $pub_id   = openssl_get_publickey($rsa_pub);
    $key_len  = openssl_pkey_get_details($pub_id)['bits'];
    $part_len = $key_len / 8;

    $base64_decoded = base64_decode($str);
    $parts          = str_split($base64_decoded, $part_len);

    foreach ($parts as $part) {
        $decrypted_temp = '';
        openssl_public_decrypt($part, $decrypted_temp, $rsa_pub);
        $decrypted .= $decrypted_temp;
    }

    return $decrypted;
}

私钥解密

function private_key_decrypt($str)
{

    $rsa_pri = file_get_contents(ROOT_PATH . 'data/rsa/private_key.pem');


    $str = str_replace(' ', '+', $str);

//    openssl_private_decrypt(base64_decode($str), $data, $rsa_pr);

    $decrypted = "";

    $pri_id = openssl_get_privatekey($rsa_pri);
    $key_len = openssl_pkey_get_details($pri_id)['bits'];
    $part_len = $key_len / 8;

    $base64_decoded = base64_decode($str);
    $parts = str_split($base64_decoded, $part_len);

    foreach ($parts as $part) {
        $decrypted_temp = '';
        openssl_private_decrypt($part, $decrypted_temp, $rsa_pri);
        $decrypted .= $decrypted_temp;
    }

    return $decrypted;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注