 |
|
การเข้ารหัสของ RSA (cryptosystem) ผมได้เขียนโค้ดการเข้ารหัสถอดรหัสแล้วติดปัญหาตรง output ที่ออกมาบางครั้งก็ออกมาสำเร็จแต่บางครั้งก็ผิดจะมีตัวอักษรขยะออกมา อยากทราบว่าเกิดจากส่วนไหนได้บ้างครับ

เข้ารหัสได้

มีอักษรขยะและเข้ารหัสผิด
Code (PHP)
<?php
$plaintext = "Helloworld";
echo encrypt_RSA($plaintext);
// 1778686828772858572948091
function encrypt_RSA($text)
{
$a = [];
$b = [];
$p = 0;
$q = 0;
while (true) {
$p = rand(1, 30);
if (findPrime($p) == true) {
break;
}
}
while (true) {
$q = rand(1,30);
if (findPrime($q) == true) {
break;
}
}
$n = $p * $q;
while (true) {
$n1 = (($p - 1) * ($q - 1));
$e = rand(1, $n1);
if (gcd($e, $n1) == 1) {
break;
}
}
echo "Public key: " . $n . " , " . $e;
print("\n");
for ($i = 0; $i < $n1 - 1; $i++) {
if (($i * $e) % $n1 == 1) {
(float)$d = $i;
break;
}
}
echo "Private key: " . $d;
for ($i = 0; $i < strlen($text); $i++) {
$t = toNum($text[$i]);
$t = myPowMod($t, $e, $n);
array_push($a, $t);
$t = toText($t);
array_push($b, chr($t));
}
for ($x = 0; $x < count($a); $x++) {
echo $a[$x] . "";
}
print("\n");
for ($x = 0; $x < count($b); $x++) {
echo $b[$x] . "";
}
print("\n");
$a = null;
$b = null;
}
function decrypt_RSA($text)
{
$a = [];
$b = [];
$p = 0;
$q = 0;
$textLength = strlen($text);
$textN=[];
while (true) {
$p = rand(1, 50);
if (findPrime($p) == true) {
break;
}
}
while (true) {
$q = rand(1, 50);
if (findPrime($q) == true) {
break;
}
}
$n = $p * $q;
while (true) {
$n1 = ($p - 1) * ($q - 1);
$e = rand(1, $n1);
if (gcd($e, $n1) == 1) {
break;
}
}
echo "Public key: " . $n . " , " . $e;
print("\n");
for ($i = 0; $i < $n1 - 1; $i++) {
if (($i * $e) % $n1 == 1) {
(float)$d = $i;
break;
}
}
echo "Private key: " . $d;
$textLength = strlen($text);
$textN=[];
for ($i = 0; $i < strlen($text); $i++) {
$t = toNum($text[$i]);
$t = myPowMod($t, $e, $n);
$t = toText($t);
echo chr($t);
}
//echo $b . "";
// print_r($t);
// print("\n");
return 0;
}
function toNum($a)
{
$a = ord($a) - (ord('z') - ord('a'));
return $a;
}
function toText($a)
{
$a = $a + (ord('z') - ord('a'));
return $a;
}
function myPowMod($a, $b, $c)
{
$x = 1;
$a = $a % $c;
if ($a == 0) {
return 0;
}
while ($b > 0) {
if (($b & 1) == 1) {
$x = ($x * $a) % $c;
}
$b = (int)($b / 2);
$a = ($a * $a) % $c;
}
return $x;
}
function gcd($a, $b)
{
if ($a > $b) {
$small = $b;
} else {
$small = $a;
}
for ($i = 1; $i < $small + 1; $i++) {
if (($a % $i == 0) && ($b % $i == 0)) {
$gcd = $i;
}
}
return $gcd;
}
function findPrime($a)
{
for ($i = 2; $i < $a - 1; $i++) {
if ($a % $i == 0) {
return 0;
}
}
return 1;
}
Tag : PHP
|
|
 |
 |
 |
 |
Date :
2021-11-02 16:09:40 |
By :
fookpannawit |
View :
622 |
Reply :
1 |
|
 |
 |
 |
 |
|
|
|
 |