RSA 加密解密

/**
 * RSA簽名
 * @param $data 待簽名數(shù)據(jù)
 * @param $private_key_path 商戶私鑰文件路徑
 * @return string
 */
function rsaSign($data, $private_key_path) {
    $priKey = file_get_contents($private_key_path);
    $res = openssl_get_privatekey($priKey);
    openssl_sign($data, $sign, $res);
    openssl_free_key($res);
    //base64編碼
    $sign = base64_encode($sign);
    return $sign;
}

/**
 * RSA驗(yàn)簽
 * @param $data 待簽名數(shù)據(jù)
 * @param $ali_public_key_path 支付寶的公鑰文件路徑
 * @param $sign 要校對(duì)的的簽名結(jié)果
 * @return bool
 */
function rsaVerify($data, $ali_public_key_path, $sign)  {
    $pubKey = file_get_contents($ali_public_key_path);
    $res = openssl_get_publickey($pubKey);
    $result = (bool)openssl_verify($data, base64_decode($sign), $res);
    openssl_free_key($res);
    return $result;
}

/**
 * RSA加密
 * @param $content  需要加密后內(nèi)容,明文
 * @param $public_key_path 商戶公鑰文件路徑
 * @return string
 */
function RsaEncrypt($content, $public_key_path){
    $pubKey = file_get_contents($public_key_path);
    $res = openssl_get_publickey($pubKey);
    //把需要加密的內(nèi)容,按128位拆開(kāi)解密
    $result  = '';
    for($i = 0; $i < strlen($content)/128; $i++  ) {
        $data = substr($content, $i * 128, 128);
        openssl_public_encrypt ($data, $encrypt, $res);
        $result .= $encrypt;
    }
    $result = base64_encode($result);
    openssl_free_key($res);
    return $result;
}

/**
 * RSA解密
 * @param $content 需要解密的內(nèi)容,密文
 * @param $private_key_path 商戶私鑰文件路徑
 * @return string
 */
function rsaDecrypt($content, $private_key_path) {
    $priKey = file_get_contents($private_key_path);
    $res = openssl_get_privatekey($priKey);
    //用base64將內(nèi)容還原成二進(jìn)制
    $content = base64_decode($content);
    //把需要解密的內(nèi)容,按128位拆開(kāi)解密
    $result  = '';
    for($i = 0; $i < strlen($content)/128; $i++  ) {
        $data = substr($content, $i * 128, 128);
        openssl_private_decrypt($data, $decrypt, $res);
        $result .= $decrypt;
    }
    openssl_free_key($res);
    return $result;
}

備注

秘鑰生成方法參考地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容