RSA encryption process in PHP

In an attempt to understand the asymmetric encryption process, I set out a simple PHP script for encrypting and decrypting primes. I noticed that after a while the data for encrypting / decrypting the algorithm will fail, since the decrypted and initial numbers do not match. I set up a loop to see how the algorithm will work when encrypting and decrypting 100 numbers, and after number 32 the process falls apart.

Is it because 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']); } ?> 

Output from the loop

+4
source share
2 answers

http://en.wikipedia.org/wiki/RSA_(algorithm)

2.2 Encryption:

[...] Bob then wants to send a message to M Alice. He first turns M into an integer m, so 0 โ‰ค m <n using a consistent reversible protocol known as the padding scheme .... Alice passes her public key (n, e) to Bob and saves

This is not done here, so you need to use larger factorizations.

+2
source

The problem is the small values โ€‹โ€‹of $p and $q . As we noticed in the comments, the larger value of $n=$p*$q starts to come back later.

Problems begin when $i>$n , then encription / decription returns the wrong numbers.

What to do? In real problems, $p and $q are huge numbers. The message is also split into a smaller one and provides a lot of values โ€‹โ€‹as a stream. For example, you can decrypt parts of your number and then sum it up to get the final value. In more complex cases, encode each character as a number and encode / decode them one at a time.

+1
source

Source: https://habr.com/ru/post/1480694/


All Articles