经常要跟java对接口用到RSA加解密及签名验签,现把方法记录下来方便用时查看:
class Rsa
{
const MAX_ENCRYPT_BLOCK = 117;
const MAX_DECRYPT_BLOCK = 128;
/**
* 私钥加密
* @param $plainString
* @param $privateKey
* @return string
*/
public static function priEncrypt($plainString, $privateKey)
{
$encryptedString = "";
$strlen = strlen($plainString);
if ($strlen < 118) {
openssl_private_encrypt($plainString, $encryptedString, self::conertKey($privateKey,"pri"));//私钥加密
} else {
foreach (str_split($plainString, self::MAX_ENCRYPT_BLOCK) as $chunk) {
openssl_private_encrypt($chunk, $chunkString, self::conertKey($privateKey,"pri"));
$encryptedString .= $chunkString;
}
}
return $encryptedString;
}
/**
* 私钥解密
* @param $encryptedString
* @param $priva