关于php rsa加密处理
最近刚好需要跟一个第三方系统对接几个接口,对方要求post数据需要rsa加密,于是百度搜了一下php关于rsa加密的处理,然后大家可能就会跟我一样搜出以下示例:
/**
* @uses 公钥加密
* @param string $data
* @return null|string
*/
public function publicEncrypt($data = '') {
if (!is_string($data)) {
return null;
}
return openssl_public_encrypt($data, $encrypted, $this->_getPublicKey()) ? base64_encode($encrypted) : null;
}
于是开开心心的复制到自己项目稍微修改修改后测试,简简单单传几个字符串进去:
<?php
$string = '基督教解决基督教解决决';
$ret = publicEncrypt($string);
var_dump($ret);
/**
* @uses 公钥加密
* @param string $data
* @return null|string
*/
function publicEncrypt($data = '') {
$publicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiX1bIq02AFypLOJ4byShfo6+D6pj0rQrdAtZ8Bb2Z4YwdCZS5vlEduBiVCZSKfF70M0nk4gMqhAKcgwqWxgI1/j8OrX401AssfaiXr2JqsAl679s+Xlwe0jppNe1832+3g0YOawDTpAQsUJDu1DpnyGnUz0qeac0/GiAJlXzKUP+/3db8haDuOkgYrT8A6twGAm7YwIuliieDWDcUS/CQzXGRtwtZQqUJDQsWC1lCML1kRUjbZ2EM2EzyttgHN0SsNryhVLHXSFXpDWbeqQwk36axojGF1lbg/oVQy+BnYJx8pKpTgSwIDAQAB';
$publicKey = "-----BEGIN PUBLIC KEY-----\n" .
wordwrap($publicKey, 64, "\n", true) .
"\n-----END PUBLIC KEY-----";
if (!is_string($data)) {
return null;
}
return openssl_public_encrypt($data, $encrypted, $publicKey) ? base64_encode($encrypted) : null;
}
程序打印:
string(344) "HSqVQbyhmWYrptvgzK+ggqmma88QRFVJerXTrZ+RpYqhZr/Dr9au9wxX+aAYy1wRh0eBk+fIpU4wkEZs6P5yozf5e/rAAEYUOImTJZcOvZqr89znT3yqaV8ME+vR16FLK5sk3BwgpOWI6X+wBwU2cLnHKDdj9RpYWAYhi/mn8XJj4/srKZbSgAjvzWqZI9gfqiJNdz8kf/MPtQ65cSlAhvh4eByY8cLGfgUXV0dxzWAkwTSPl2faSq3GHsNMXnxwoNjIvqz/IuZavqABNVZCwrZC3ZVb+Op7wF9GxrkIdJYzmHpX/wNn1DPLHUvghtO/WmfN4Jb2ZVzTsneB5B3Z6g=="
看似一切正常,实际项目中对一个比较长的json字符串进行加密时,发现返回了null,追溯了一下openssl_public_encrypt
这个函数此时是返回false的,表示加密失败。传入不同长度的字符串测试了几遍后发现字符串长度超过100多之后就会出现加密失败的问题,参考了一下对方发来的java加密示例
/**
* 用公钥加密
* @param data
* @param publicKey
* @return
* @throws Exception
*/
public static String rsaEncrypt(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.getBytes().length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
// 加密后的字符串
return Base64.getEncoder().encodeToString(encryptedData);
}
发现他们是需要对要加密的字符串进行一个分割操作,于是有了以下修改后的版本:
/**
* 公钥加密
* @param string $data
* @return null|string
*/
public function publicEncrypt($data = '')
{
if (!is_string($data)) {
return null;
}
$dataLength = mb_strlen($data);
$offet = 0;
$length = 128;
$i = 0;
$string = '';
while ($dataLength - $offet > 0) {
if ($dataLength - $offet > $length) {
$str = mb_substr($data, $offet, $length);
} else {
$str = mb_substr($data, $offet, $dataLength - $offet);
}
$encrypted = '';
openssl_public_encrypt($str,$encrypted, $this->rsaPublicKey, OPENSSL_PKCS1_OAEP_PADDING);//这个OPENSSL_PKCS1_OAEP_PADDING是对方要求要用这种padding方式
$string .= $encrypted;
$i ++;
$offet = $i * $length;
}
return base64_encode($string);
}
目前测试没有再发现加密失败问题~
下面贴一个比较完整的示例:
<?php
namespace Common\Logic;
class Rsa
{
private $rsaPrivateKey = '';
private $rsaPublicKey = '';
private $privateKeyRule = '';
private $publicKeyRule = '';
/**
* Rsa constructor.
* @param $privateKeyRule 私钥路径
* @param $publicKeyRule 公钥路径
* @param string $rsaPrivateKey 私钥 一行字符串的形式
* @param string $rsaPublicKey 公钥 一行字符串的形式
*/
public function __construct($privateKeyRule, $publicKeyRule, $rsaPrivateKey = '', $rsaPublicKey = '')
{
$this->rsaPrivateKey = $rsaPrivateKey;
$this->rsaPublicKey = $rsaPublicKey;
$this->privateKeyRule = $privateKeyRule;
$this->publicKeyRule = $publicKeyRule;
$this->rsaPublicKey = "-----BEGIN PUBLIC KEY-----\n" .
wordwrap($this->rsaPublicKey, 64, "\n", true) .
"\n-----END PUBLIC KEY-----";
if (empty($rsaPrivateKey) && empty($rsaPublicKey)) {
$this->rsaPrivateKey = $this->getPrivateKey();
$this->rsaPublicKey = $this->getPublicKey();
}
}
/**
* 获取私钥
* @return bool|resource
*/
private function getPrivateKey()
{
$absPath = $this->privateKeyRule;
$content = file_get_contents($absPath);
return openssl_pkey_get_private($content);
}
/**
* 获取公钥
* @return bool|resource
*/
private function getPublicKey()
{
$absPath = $this->privateKeyRule;
$content = file_get_contents($absPath);
return openssl_pkey_get_public($content);
}
/**
* 私钥加密
* @param string $data
* @return null|string
*/
public function privEncrypt($data = '')
{
if (!is_string($data)) {
return null;
}
return openssl_private_encrypt($data,$encrypted, $this->rsaPrivateKey) ? base64_encode($encrypted) : null;
}
/**
* 公钥加密
* @param string $data
* @return null|string
*/
public function publicEncrypt($data = '')
{
if (!is_string($data)) {
return null;
}
$dataLength = mb_strlen($data);
$offet = 0;
$length = 128;
$i = 0;
$string = '';
while ($dataLength - $offet > 0) {
if ($dataLength - $offet > $length) {
$str = mb_substr($data, $offet, $length);
} else {
$str = mb_substr($data, $offet, $dataLength - $offet);
}
$encrypted = '';
openssl_public_encrypt($str,$encrypted, $this->rsaPublicKey, OPENSSL_PKCS1_OAEP_PADDING);
$string .= $encrypted;
$i ++;
$offet = $i * $length;
}
return base64_encode($string);
}
/**
* 私钥解密
* @param string $encrypted
* @return null
*/
public function privDecrypt($encrypted = '')
{
if (!is_string($encrypted)) {
return null;
}
return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, $this->rsaPrivateKey)) ? $decrypted : null;
}
/**
* 公钥解密
* @param string $encrypted
* @return null
*/
public function publicDecrypt($encrypted = '')
{
if (!is_string($encrypted)) {
return null;
}
return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, $this->rsaPublicKey)) ? $decrypted : null;
}
}
调用:
<?php
namespace Common\Logic;
class Test
{
private $publicKey = 'MIIBIjANBgkqhkiG9w0BAQEkdkkddUz0qeac0/GiAJlXzKUP+/3db8haDuOkgYrT8A6twGAm7YwIuliiQYxjdUVdFLdnPUK3TJm38H+79lpqIGv1gseDWDcUS/CQzXGRtwtZQqUJDQsWC1lCML1kRUjbZ2EM2EzyttgHN0SsNryhVLHXSFXpDWbeqQwk36axojGF1lbg/oVQy+BnYJx8pKpTgSwIDAQAB';
private $privateKey = 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCJfVsirTYAXKks4nhvJKF+jr4PqmPStCt0C1nwFvZnhjB0JlLm+UR24GJUJlIp8XvQzSeTiAyqEApyDCpbGAjX+Pw6tfjTUCyx9qJevYmqwCXrv2z5eXB7SOmkB2T0F9spA54+zs8fb6kczOOcdirhnvYTDmIvMUhFfBrIg02GssMxZjpaz70J94V8tKcNs9raHxdkkdVh5+GAL4+DYPI4RxHctGNbrv4farojZLY/nSYOLI7forzw9K3wwwtvMbHJ9vSRfAfwyAO5wdFarLeqZePtxSFgrmPQK3gLFvOhAoGAFE04C2idVeV6gG/PBXyMMskJN5WZGCjV4WW906SlYaGbHnUphNn8+oG88Vy2WZSjAtUsEwW0hk1OotqWrByEoEeJerYF5NokRcmRo/esBHEq1tvTu5xTSAPc3c+I3UEVIVaBnqZiZjQrpl78Cxr5+A2kFiIEFZmZ3MHWWhA7Hd0CgYAL3bNMVFJ8gAZ3WaR7LCiPd7SaFhuZ8CMu3fzP1j1n9rgzNz3dVIUXt++JMyFIbpuALQi0hxwBTGT8xMox8T0Mcy3rDyDPdlQpLMGuFMcBRDCI+C0IT03NP4jQ6a7/Izov9lSXU10QW7KC3PyQbnuSCCvrMSpuQT8A2/HiQtBdNA==';
/**
@param $data array
**/
public function rsaData($data)
{
$data = json_encode($data);
$rsa = new Rsa('', '', $this->privateKey, $this->publicKey);
//加密数据包
$encryptData = $rsa->publicEncrypt($data);
return $encryptData;
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
巧了,我最近也需要用到这个
RSA算法能加密的明文长度和密钥是紧密相关的,更长的密钥可以加密更长的明文,但是加解密也会消耗更多的硬件资源。
假如有 明文长度m,密钥长度n,那么必有
0 < m < n
。如果小于n长度就需要进行padding,一般使用的padding标准有NoPPadding、OAEPPadding、PKCS1Padding等,其中PKCS#1建议的padding就占用了11个字节。这样,对于1024长度的密钥。128字节(1024bits)减去11字节正好是117字节,但对于RSA加密来讲,padding也是参与加密的,所以,依然按照1024bits去理解,但实际的明文只有117字节了。
所以如果要对任意长度的数据进行加密,就需要将数据分段后进行逐一加密,并将结果进行拼接。同样,解码也需要分段解码,并将结果进行拼接。
贴个完整版的就好了,直接好像运行不了,我改了下可以了
github.com/plugins-world/PhpSuppor... 这个看看?公钥加密,私钥解密。
github.com/plugins-world/PhpSuppor... 还有这个,私钥加密,公钥解密。