为了理解非对称加密过程,我概述了一个简单的 PHP 脚本来加密和解密简单数字。我注意到,在给定数字加密/解密一段时间后,算法会失败,因为解密后的数字和初始数字不匹配。我放了一个循环来查看算法在加密和解密 100 个数字时的执行情况,而在数字 32 之后,这个过程就崩溃了。
这是因为 p*q = 33 吗?
<?php
# Test encrypto algo
// Choose prime keys
$p = 47; $q = 71;
// Compute n = pq
$n = $p*$q;
// Choose e such that 1 < e < f(n) and e and n are coprime
$e = 79;
// Compute a value for d such that (d * e) % f(n) = 1
$d = 1019;
// Compute f(n) = (p-1)(q-1)
$z = ($p - 1)*($q - 1);
// Create public and private keys
$pubK = array('n' => $n, 'e' => $e);
$privK = array('n'=> $n, 'd' => $d);
// Boundary for loop
$l = 100;
// Perform encypt/decrypt on 1..100
for($i = 1; $i <= $l; $i++)
{
$enc = enc($i, $pubK);
$dec = dec($enc, $privK);
print "encrypted <b>$i</b> = $enc decrypted $enc = <b>$dec</b> ";
if($i == $dec)
print "Success<br>";
else
print "Fail<br>";
}
// Encrypt sample with public key
function enc($sample, $key)
{
return bcmod(bcpow($sample,$key['e']),$key['n']);
}
// Decrypt encrypted sample with private key
function dec($sample, $key)
{
return bcmod(bcpow($sample, $key['d']),$key['n']);
}
?>