如何使用 public/private RSA 密钥签署一些数据?
How to sign some data using public/private RSA key?
我有一个 RSA public/private 密钥 xml 文件。我想用它来签署一些数据,使用以下 classes 这是我如何使用 class:
$processor = new RSAProcessor("certificate.xml", RSAKeyType:: XMLFile);
$data = $processor->sign($data);
print(base64_encode($data));
但我收到错误:WARNING: str_repeat(): Second argument has to be greater than or equal to 0 in RSA.php on line 81
。如何解决?我想 php 7.2 的某些东西已经过时了?感谢您的帮助,我应该在 class 中做哪些更改才能避免此错误?
RSA class:
define("BCCOMP_LARGER", 1);
class RSA {
static function rsa_encrypt($message, $public_key, $modulus, $keylength) {
$padded = RSA::add_PKCS1_padding($message, true, $keylength / 8);
$number = RSA::binary_to_number($padded);
$encrypted = RSA::pow_mod($number, $public_key, $modulus);
$result = RSA::number_to_binary($encrypted, $keylength / 8);
return $result;
}
static function rsa_decrypt($message, $private_key, $modulus, $keylength) {
$number = RSA::binary_to_number($message);
$decrypted = RSA::pow_mod($number, $private_key, $modulus);
$result = RSA::number_to_binary($decrypted, $keylength / 8);
return RSA::remove_PKCS1_padding($result, $keylength / 8);
}
static function rsa_sign($message, $private_key, $modulus, $keylength) {
$padded = RSA::add_PKCS1_padding($message, false, $keylength / 8);
$number = RSA::binary_to_number($padded);
$signed = RSA::pow_mod($number, $private_key, $modulus);
$result = RSA::number_to_binary($signed, $keylength / 8);
return $result;
}
static function rsa_verify($message, $public_key, $modulus, $keylength) {
return RSA::rsa_decrypt($message, $public_key, $modulus, $keylength);
}
static function rsa_kyp_verify($message, $public_key, $modulus, $keylength) {
$number = RSA::binary_to_number($message);
$decrypted = RSA::pow_mod($number, $public_key, $modulus);
$result = RSA::number_to_binary($decrypted, $keylength / 8);
return RSA::remove_KYP_padding($result, $keylength / 8);
}
static function pow_mod($p, $q, $r) {
$factors = array();
$div = $q;
$power_of_two = 0;
while(bccomp($div, "0") == BCCOMP_LARGER) {
$rem = bcmod($div, 2);
$div = bcdiv($div, 2);
if($rem) array_push($factors, $power_of_two);
$power_of_two++;
}
$partial_results = array();
$part_res = $p;
$idx = 0;
foreach($factors as $factor) {
while($idx < $factor)
{
$part_res = bcpow($part_res, "2");
$part_res = bcmod($part_res, $r);
$idx++;
}
array_push($partial_results, $part_res);
}
$result = "1";
foreach($partial_results as $part_res)
{
$result = bcmul($result, $part_res);
$result = bcmod($result, $r);
}
return $result;
}
static function add_PKCS1_padding($data, $isPublicKey, $blocksize)
{
$pad_length = $blocksize - 3 - strlen($data);
if($isPublicKey)
{
$block_type = "\x02";
$padding = "";
for($i = 0; $i < $pad_length; $i++)
{
$rnd = mt_rand(1, 255);
$padding .= chr($rnd);
}
}
else
{
$block_type = "\x01";
$padding = str_repeat("\xFF", $pad_length);
}
return "\x00" . $block_type . $padding . "\x00" . $data;
}
static function remove_PKCS1_padding($data, $blocksize)
{
assert(strlen($data) == $blocksize);
$data = substr($data, 1);
if($data{0} == '[=12=]')
die("Block type 0 not implemented.");
assert(($data{0} == "\x01") || ($data{0} == "\x02"));
$offset = strpos($data, "[=12=]", 1);
return substr($data, $offset + 1);
}
static function remove_KYP_padding($data, $blocksize)
{
assert(strlen($data) == $blocksize);
$offset = strpos($data, "[=12=]");
return substr($data, 0, $offset);
}
static function binary_to_number($data)
{
$base = "256";
$radix = "1";
$result = "0";
for($i = strlen($data) - 1; $i >= 0; $i--)
{
$digit = ord($data{$i});
$part_res = bcmul($digit, $radix);
$result = bcadd($result, $part_res);
$radix = bcmul($radix, $base);
}
return $result;
}
static function number_to_binary($number, $blocksize)
{
$base = "256";
$result = "";
$div = $number;
while($div > 0)
{
$mod = bcmod($div, $base);
$div = bcdiv($div, $base);
$result = chr($mod) . $result;
}
return str_pad($result, $blocksize, "\x00", STR_PAD_LEFT);
}
}
RSAProcessor class:
class RSAProcessor
{
private $public_key = null;
private $private_key = null;
private $modulus = null;
private $key_length = "1024";
public function __construct($xmlRsakey=null,$type=null)
{
$xmlObj = null;
if ($xmlRsakey==null) {
$xmlObj = simplexml_load_file("xmlfile/RSAKey.xml");
} elseif ($type==RSAKeyType::XMLFile) {
$xmlObj = simplexml_load_file($xmlRsakey);
} else {
$xmlObj = simplexml_load_string($xmlRsakey);
}
$this->modulus = RSA::binary_to_number(base64_decode($xmlObj->Modulus));
$this->public_key = RSA::binary_to_number(base64_decode($xmlObj->Exponent));
$this->private_key = RSA::binary_to_number(base64_decode($xmlObj->D));
$this->key_length = strlen(base64_decode($xmlObj->Modulus))*8;
}
public function getPublicKey() {
return $this->public_key;
}
public function getPrivateKey() {
return $this->private_key;
}
public function getKeyLength() {
return $this->key_length;
}
public function getModulus() {
return $this->modulus;
}
public function encrypt($data) {
return base64_encode(RSA::rsa_encrypt($data,$this->public_key,$this->modulus,$this->key_length));
}
public function dencrypt($data) {
return RSA::rsa_decrypt($data,$this->private_key,$this->modulus,$this->key_length);
}
public function sign($data) {
return RSA::rsa_sign($data,$this->private_key,$this->modulus,$this->key_length);
}
public function verify($data) {
return RSA::rsa_verify($data,$this->public_key,$this->modulus,$this->key_length);
}
}
class RSAKeyType{
const XMLFile = 0;
const XMLString = 1;
}
certificate.xml:
<RSAKeyValue>
<Modulus>tCZiqDS5BVQQZDBUYbyeoP4rENN4mX5FZJjjMNfGbyzfzH45RY2/YsMaY0yI1jMCOpukvkUyl153tcn0LXhMCDdsEhhZPoKbPUGMniKtFGjs18rv/b5FFUUW1utgwoL8+WJqjOqhQGgvbja63X9+WMFP0nM3d8yudn9C/X55KyM=</Modulus>
<Exponent>AQAB</Exponent>
<P>5HXvmU4IfqUG2jFLSqi/BMEQ3x1NsUDvx3zN5O1p9yLLspJ4sqAt4RUkxzcGodYgBSdXsR9IGcPwjQfbx3a7nQ==</P>
<Q>yd2hDCF/5Zqtz9DXjY1NRYGvBjTS4AQn83ERR46Y5eBSnLjpVjv6gPfARuhsUP44nikrQPvwPnjxQcOhJaOlvw==</Q>
<DP>ztuqUplBP8qU5cN0dOlN7DQT3rFdw30Unv/2Pa5qIAc1gT72YmZ+pCrM3kSIkMicvY3d7NZyJkIv8MKI0ZZEUQ==</DP>
<DQ>QFLJ5YarLWubZPQEK4vSCornTY/5ff51CIKH4ghTOjS/vkbBu4PDL+NCNpYLJcfMHMG7kap2BEIfhjgjGk5KGw==</DQ>
<InverseQ>WE6TqpcexQJwt9Mnp1FbeLtarBcFkXVdBauouFKHcbHCfQjA3IjUrGTxgSO74O/4QSKqaF2gnlL6GI7gKuGbzQ==</InverseQ> <D>czYtWDfHsFGv3fNOs+cGaB3E+xDTiw7HYGuquJz2qjk/s69x/zqFEKuIH8Ndq+eZYFQUCx+EGGxxENDkmYPa0z8wbfFI6JEHpxaLmQfpkkbSL1BJIp9Z5BNM2gy6jJqgbWwQPcN/4jpiMefHZWAqhMKqenUu1KIq1ZX6Bz5xKYk=</D>
</RSAKeyValue>
感谢您的帮助,我应该如何更改 class 以避免此错误?
在我本地环境下,代码运行流畅,在http://phpfiddle.org/(PHP7.0.33)上也是!然而,对于后者,密钥必须作为字符串传递,因为在线没有可用的文件系统:
$privateKey = "<RSAKeyValue>...</RSAKeyValue>";
$processor = new RSAProcessor($privateKey, RSAKeyType::XMLString);
另一方面,相同的代码在 http://sandbox.onlinephpfunctions.com/ (PHP 7.01 - PHP 7.3.5) 上失败,并出现与您相同的错误消息。原因是 simplexml_load_string()
方法被禁用了。因此无法加载密钥,RSAProcessor
-class的成员变量$modulus
、$key_length
、$private_key
和$public_key
得到值0
。结果,使用 $blocksize=$keylength/8
调用的方法 add_PKCS1_padding
确定 $pad_length=$blocksize-3-strlen($data)
的负值,这显然会导致错误消息 str_repeat():当调用 str_repeat("\xFF", $pad_length)
时,第二个参数必须大于或等于 0。
如果我在我的本地环境中禁用方法 simplexml_load_file
,我可以完全重现此行为。由于代码原则上有效,因此可以假设您的系统也禁用了方法,尤其是 simplexml_load_file
.
禁用的方法可以通过从 php.ini
.
的 disable_functions
列表中删除来启用
更新:
正如评论中已经提到的,RSA 得到了绝大多数图书馆的支持,例如phpseclib
, here, which also supports the key format used in your code, here.
一般来说,对于 PKCS#1,根据 RFC 8017, see also here 签名的不是数据本身,而是带有前面摘要信息(DigestInfo
值的 DER 编码)的散列。还必须指定摘要。假设您的数据(即传递给您的 RSAProcessor#sign
方法的 $data
)遵循此约定,即:
$dataToSign = 'The quick brown fox jumps over the lazy dog';
$data = hex2bin('3031300d060960864801650304020105000420' . hash('SHA256', $dataToSign, false));
以下使用 phpseclib 库(以 SHA256 作为摘要)的代码将生成 相同 签名:
include('RSA.php');
include('BigInteger.php');
$rsa = new Crypt_RSA();
$privateKey = "<RSAKeyValue>...</RSAKeyValue>";
$dataToSign = 'The quick brown fox jumps over the lazy dog';
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_XML); // private key format
$rsa->loadKey($privateKey);
$rsa->setHash('sha256'); // digest for signing
$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); // RSASSA-PKCS1-v1_5-padding
$signature = $rsa->sign($dataToSign);
echo 'Signature (hex): ' . bin2hex($signature) . "\n";
echo 'Signature (base64): ' . base64_encode($signature) . "\n";
然后两个代码都提供以下签名(十六进制字符串):
6f00eb1126470e097991aaa1e3e94b49a7b8de6c9b2bf683382f96563479b87067be20635ccc1d36fedff9d60f682fdefcb108f5351dc672ebb442e49231d0306b302b258f6b21fb724b59ad765151f6c724de214d41afa0e1b08228b070c537020df8acf9cad5f2fdde63bc698875527a52e49155bd5e2fd761f541844e92bb
更新二:
对于 SHA1,您的代码的 ID 加散列可以按如下方式确定:
$data = hex2bin('3021300906052b0e03021a05000414' . hash('SHA1', $dataToSign, false));
或
$data = hex2bin('3021300906052b0e03021a05000414' . SHA1($dataToSign, false));
hash
-function or the sha1
-function can be used. In both cases, the last parameter $raw_output
controls whether the return is a binary (TRUE
) or a hex string (FALSE
). Because of the concatenation with the ID I return the hash as hex string, do the concatenation and finally convert explicitly with hex2bin
into the binary representation. The digest ID can also be found here, page 47.
在 phpseclib 代码中
$rsa->setHash('sha1');
必须使用。
我有一个 RSA public/private 密钥 xml 文件。我想用它来签署一些数据,使用以下 classes 这是我如何使用 class:
$processor = new RSAProcessor("certificate.xml", RSAKeyType:: XMLFile);
$data = $processor->sign($data);
print(base64_encode($data));
但我收到错误:WARNING: str_repeat(): Second argument has to be greater than or equal to 0 in RSA.php on line 81
。如何解决?我想 php 7.2 的某些东西已经过时了?感谢您的帮助,我应该在 class 中做哪些更改才能避免此错误?
RSA class:
define("BCCOMP_LARGER", 1);
class RSA {
static function rsa_encrypt($message, $public_key, $modulus, $keylength) {
$padded = RSA::add_PKCS1_padding($message, true, $keylength / 8);
$number = RSA::binary_to_number($padded);
$encrypted = RSA::pow_mod($number, $public_key, $modulus);
$result = RSA::number_to_binary($encrypted, $keylength / 8);
return $result;
}
static function rsa_decrypt($message, $private_key, $modulus, $keylength) {
$number = RSA::binary_to_number($message);
$decrypted = RSA::pow_mod($number, $private_key, $modulus);
$result = RSA::number_to_binary($decrypted, $keylength / 8);
return RSA::remove_PKCS1_padding($result, $keylength / 8);
}
static function rsa_sign($message, $private_key, $modulus, $keylength) {
$padded = RSA::add_PKCS1_padding($message, false, $keylength / 8);
$number = RSA::binary_to_number($padded);
$signed = RSA::pow_mod($number, $private_key, $modulus);
$result = RSA::number_to_binary($signed, $keylength / 8);
return $result;
}
static function rsa_verify($message, $public_key, $modulus, $keylength) {
return RSA::rsa_decrypt($message, $public_key, $modulus, $keylength);
}
static function rsa_kyp_verify($message, $public_key, $modulus, $keylength) {
$number = RSA::binary_to_number($message);
$decrypted = RSA::pow_mod($number, $public_key, $modulus);
$result = RSA::number_to_binary($decrypted, $keylength / 8);
return RSA::remove_KYP_padding($result, $keylength / 8);
}
static function pow_mod($p, $q, $r) {
$factors = array();
$div = $q;
$power_of_two = 0;
while(bccomp($div, "0") == BCCOMP_LARGER) {
$rem = bcmod($div, 2);
$div = bcdiv($div, 2);
if($rem) array_push($factors, $power_of_two);
$power_of_two++;
}
$partial_results = array();
$part_res = $p;
$idx = 0;
foreach($factors as $factor) {
while($idx < $factor)
{
$part_res = bcpow($part_res, "2");
$part_res = bcmod($part_res, $r);
$idx++;
}
array_push($partial_results, $part_res);
}
$result = "1";
foreach($partial_results as $part_res)
{
$result = bcmul($result, $part_res);
$result = bcmod($result, $r);
}
return $result;
}
static function add_PKCS1_padding($data, $isPublicKey, $blocksize)
{
$pad_length = $blocksize - 3 - strlen($data);
if($isPublicKey)
{
$block_type = "\x02";
$padding = "";
for($i = 0; $i < $pad_length; $i++)
{
$rnd = mt_rand(1, 255);
$padding .= chr($rnd);
}
}
else
{
$block_type = "\x01";
$padding = str_repeat("\xFF", $pad_length);
}
return "\x00" . $block_type . $padding . "\x00" . $data;
}
static function remove_PKCS1_padding($data, $blocksize)
{
assert(strlen($data) == $blocksize);
$data = substr($data, 1);
if($data{0} == '[=12=]')
die("Block type 0 not implemented.");
assert(($data{0} == "\x01") || ($data{0} == "\x02"));
$offset = strpos($data, "[=12=]", 1);
return substr($data, $offset + 1);
}
static function remove_KYP_padding($data, $blocksize)
{
assert(strlen($data) == $blocksize);
$offset = strpos($data, "[=12=]");
return substr($data, 0, $offset);
}
static function binary_to_number($data)
{
$base = "256";
$radix = "1";
$result = "0";
for($i = strlen($data) - 1; $i >= 0; $i--)
{
$digit = ord($data{$i});
$part_res = bcmul($digit, $radix);
$result = bcadd($result, $part_res);
$radix = bcmul($radix, $base);
}
return $result;
}
static function number_to_binary($number, $blocksize)
{
$base = "256";
$result = "";
$div = $number;
while($div > 0)
{
$mod = bcmod($div, $base);
$div = bcdiv($div, $base);
$result = chr($mod) . $result;
}
return str_pad($result, $blocksize, "\x00", STR_PAD_LEFT);
}
}
RSAProcessor class:
class RSAProcessor
{
private $public_key = null;
private $private_key = null;
private $modulus = null;
private $key_length = "1024";
public function __construct($xmlRsakey=null,$type=null)
{
$xmlObj = null;
if ($xmlRsakey==null) {
$xmlObj = simplexml_load_file("xmlfile/RSAKey.xml");
} elseif ($type==RSAKeyType::XMLFile) {
$xmlObj = simplexml_load_file($xmlRsakey);
} else {
$xmlObj = simplexml_load_string($xmlRsakey);
}
$this->modulus = RSA::binary_to_number(base64_decode($xmlObj->Modulus));
$this->public_key = RSA::binary_to_number(base64_decode($xmlObj->Exponent));
$this->private_key = RSA::binary_to_number(base64_decode($xmlObj->D));
$this->key_length = strlen(base64_decode($xmlObj->Modulus))*8;
}
public function getPublicKey() {
return $this->public_key;
}
public function getPrivateKey() {
return $this->private_key;
}
public function getKeyLength() {
return $this->key_length;
}
public function getModulus() {
return $this->modulus;
}
public function encrypt($data) {
return base64_encode(RSA::rsa_encrypt($data,$this->public_key,$this->modulus,$this->key_length));
}
public function dencrypt($data) {
return RSA::rsa_decrypt($data,$this->private_key,$this->modulus,$this->key_length);
}
public function sign($data) {
return RSA::rsa_sign($data,$this->private_key,$this->modulus,$this->key_length);
}
public function verify($data) {
return RSA::rsa_verify($data,$this->public_key,$this->modulus,$this->key_length);
}
}
class RSAKeyType{
const XMLFile = 0;
const XMLString = 1;
}
certificate.xml:
<RSAKeyValue>
<Modulus>tCZiqDS5BVQQZDBUYbyeoP4rENN4mX5FZJjjMNfGbyzfzH45RY2/YsMaY0yI1jMCOpukvkUyl153tcn0LXhMCDdsEhhZPoKbPUGMniKtFGjs18rv/b5FFUUW1utgwoL8+WJqjOqhQGgvbja63X9+WMFP0nM3d8yudn9C/X55KyM=</Modulus>
<Exponent>AQAB</Exponent>
<P>5HXvmU4IfqUG2jFLSqi/BMEQ3x1NsUDvx3zN5O1p9yLLspJ4sqAt4RUkxzcGodYgBSdXsR9IGcPwjQfbx3a7nQ==</P>
<Q>yd2hDCF/5Zqtz9DXjY1NRYGvBjTS4AQn83ERR46Y5eBSnLjpVjv6gPfARuhsUP44nikrQPvwPnjxQcOhJaOlvw==</Q>
<DP>ztuqUplBP8qU5cN0dOlN7DQT3rFdw30Unv/2Pa5qIAc1gT72YmZ+pCrM3kSIkMicvY3d7NZyJkIv8MKI0ZZEUQ==</DP>
<DQ>QFLJ5YarLWubZPQEK4vSCornTY/5ff51CIKH4ghTOjS/vkbBu4PDL+NCNpYLJcfMHMG7kap2BEIfhjgjGk5KGw==</DQ>
<InverseQ>WE6TqpcexQJwt9Mnp1FbeLtarBcFkXVdBauouFKHcbHCfQjA3IjUrGTxgSO74O/4QSKqaF2gnlL6GI7gKuGbzQ==</InverseQ> <D>czYtWDfHsFGv3fNOs+cGaB3E+xDTiw7HYGuquJz2qjk/s69x/zqFEKuIH8Ndq+eZYFQUCx+EGGxxENDkmYPa0z8wbfFI6JEHpxaLmQfpkkbSL1BJIp9Z5BNM2gy6jJqgbWwQPcN/4jpiMefHZWAqhMKqenUu1KIq1ZX6Bz5xKYk=</D>
</RSAKeyValue>
感谢您的帮助,我应该如何更改 class 以避免此错误?
在我本地环境下,代码运行流畅,在http://phpfiddle.org/(PHP7.0.33)上也是!然而,对于后者,密钥必须作为字符串传递,因为在线没有可用的文件系统:
$privateKey = "<RSAKeyValue>...</RSAKeyValue>";
$processor = new RSAProcessor($privateKey, RSAKeyType::XMLString);
另一方面,相同的代码在 http://sandbox.onlinephpfunctions.com/ (PHP 7.01 - PHP 7.3.5) 上失败,并出现与您相同的错误消息。原因是 simplexml_load_string()
方法被禁用了。因此无法加载密钥,RSAProcessor
-class的成员变量$modulus
、$key_length
、$private_key
和$public_key
得到值0
。结果,使用 $blocksize=$keylength/8
调用的方法 add_PKCS1_padding
确定 $pad_length=$blocksize-3-strlen($data)
的负值,这显然会导致错误消息 str_repeat():当调用 str_repeat("\xFF", $pad_length)
时,第二个参数必须大于或等于 0。
如果我在我的本地环境中禁用方法 simplexml_load_file
,我可以完全重现此行为。由于代码原则上有效,因此可以假设您的系统也禁用了方法,尤其是 simplexml_load_file
.
禁用的方法可以通过从 php.ini
.
disable_functions
列表中删除来启用
更新:
正如评论中已经提到的,RSA 得到了绝大多数图书馆的支持,例如phpseclib
, here, which also supports the key format used in your code, here.
一般来说,对于 PKCS#1,根据 RFC 8017, see also here 签名的不是数据本身,而是带有前面摘要信息(DigestInfo
值的 DER 编码)的散列。还必须指定摘要。假设您的数据(即传递给您的 RSAProcessor#sign
方法的 $data
)遵循此约定,即:
$dataToSign = 'The quick brown fox jumps over the lazy dog';
$data = hex2bin('3031300d060960864801650304020105000420' . hash('SHA256', $dataToSign, false));
以下使用 phpseclib 库(以 SHA256 作为摘要)的代码将生成 相同 签名:
include('RSA.php');
include('BigInteger.php');
$rsa = new Crypt_RSA();
$privateKey = "<RSAKeyValue>...</RSAKeyValue>";
$dataToSign = 'The quick brown fox jumps over the lazy dog';
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_XML); // private key format
$rsa->loadKey($privateKey);
$rsa->setHash('sha256'); // digest for signing
$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); // RSASSA-PKCS1-v1_5-padding
$signature = $rsa->sign($dataToSign);
echo 'Signature (hex): ' . bin2hex($signature) . "\n";
echo 'Signature (base64): ' . base64_encode($signature) . "\n";
然后两个代码都提供以下签名(十六进制字符串):
6f00eb1126470e097991aaa1e3e94b49a7b8de6c9b2bf683382f96563479b87067be20635ccc1d36fedff9d60f682fdefcb108f5351dc672ebb442e49231d0306b302b258f6b21fb724b59ad765151f6c724de214d41afa0e1b08228b070c537020df8acf9cad5f2fdde63bc698875527a52e49155bd5e2fd761f541844e92bb
更新二:
对于 SHA1,您的代码的 ID 加散列可以按如下方式确定:
$data = hex2bin('3021300906052b0e03021a05000414' . hash('SHA1', $dataToSign, false));
或
$data = hex2bin('3021300906052b0e03021a05000414' . SHA1($dataToSign, false));
hash
-function or the sha1
-function can be used. In both cases, the last parameter $raw_output
controls whether the return is a binary (TRUE
) or a hex string (FALSE
). Because of the concatenation with the ID I return the hash as hex string, do the concatenation and finally convert explicitly with hex2bin
into the binary representation. The digest ID can also be found here, page 47.
在 phpseclib 代码中
$rsa->setHash('sha1');
必须使用。