最近剛好需要跟一個第三方系統對接幾個介面,對方要求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 協議》,轉載必須註明作者和本文連結