PHP RSA加解密工具
阿新 • • 發佈:2018-12-11
/** * RSA加解密工具 * User: 樂楊俊 * Date: 2016/9/17 * Time: 下午4:06 */ namespace leyangjun\Lib; class CryptRsa { /** * 私鑰加密 */ public function privEncrypt($content, $privateKey) { $priKeyId = openssl_pkey_get_private($privateKey); $encrypted = ''; openssl_private_encrypt($content, $encrypted, $priKeyId); openssl_free_key($priKeyId); return base64_encode($encrypted); } /** * 公鑰解密 */ public function pubDecrypt($content, $rsaPublicKey) { $pubKeyId = openssl_pkey_get_public($rsaPublicKey); $content = base64_decode($content); $decrypted = ''; openssl_public_decrypt($content, $decrypted, $pubKeyId); openssl_free_key($pubKeyId); return $decrypted; } /** * 加密 * @param String $content 待加密內容 * @param String $path_rsa_public_key RSA公鑰路徑(絕對) */ public function encrypt($content, $rsaPublicKey) { $pubKeyId = openssl_pkey_get_public($rsaPublicKey); $encrypted = ''; openssl_public_encrypt($content, $encrypted, $pubKeyId); openssl_free_key($pubKeyId); return base64_encode($encrypted); } /** * 解密 * */ public function decrypt($content, $rsaPrivateKey) { $priKeyId = openssl_pkey_get_private($rsaPrivateKey); $content = base64_decode($content); $decrypted = ''; openssl_private_decrypt($content, $decrypted, $priKeyId); openssl_free_key($priKeyId); return $decrypted; } /** * RSA校驗 */ public function check($publicKey,$fromSign,$toSign){ $publicKeyId = openssl_pkey_get_public($publicKey); $result = openssl_verify($fromSign, base64_decode($toSign), $publicKeyId); openssl_free_key($publicKeyId); return $result === 1 ? true : false; } public function getRsaSign($signData,$rsaPrivateKey){ $privKeyId = openssl_pkey_get_private($rsaPrivateKey); $signature = ''; openssl_sign($signData, $signature, $privKeyId); openssl_free_key($privKeyId); return base64_encode($signature); } }