Reputation: 1427
I have a public key exponent (e) and public key modulus (n) which I need to use to encrypt some text. First of all - is knowing of these two values enough to be able to encrypt plaintext by RSA and send it back to owner, so he can decrypt it using his private key?
If yes, how to achieve that in phpseclib ( http://phpseclib.sourceforge.net/ ) library? Theirs examples (http://phpseclib.sourceforge.net/new/rsa/examples.html) aren't very clear. However, my understanding of RSA isn't very clear either (that's why I am currently playing with it), so I will need some help.
Sadly, this is what I have been able to do so far
define('CRYPT_RSA_EXPONENT', $e);
$rsa = new Crypt_RSA();
The Crypt_RSA class provides functions like "loadKey($key)" and "setPublicKey($key)". I guess I will be using one of them, but first I need to know public key. So .. do I know the public key? As I said, I have public key exponent and public key modulus, but is it possible to construct public key based on those two values?
I will be very happy for some explanation or working example.
Upvotes: 0
Views: 633
Reputation: 16802
Normally RSA keys are string that have both the modulo and exponent embedded within them. eg.
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0
FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/
3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB
-----END PUBLIC KEY-----
...or...
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZw== phpseclib-generated-key
...etc.
If you're working with them as distinct "objects" then it makes me wonder if you're trying to do textbook RSA, which shouldn't really be used outside of the classroom.
In any event,
<?php
include('Crypt/RSA.php');
include('Math/BigInteger.php');
$rsa = new Crypt_RSA();
$rsa->loadKey(array(
'e' => new Math_BigInteger('...'),
'n' => new Math_BigInteger('...')
));
Math_BigInteger itself can optionally take two parameters. The second tells it the format, be it base-10, base-256, base-16, base-2, etc. If you have a base64 encoded number you'll need to pass it through base64_decode and (probably) tell Math_BigInteger that it's a base-256 number. By default Math_BigInteger assumes numbers are base-10.
To do textbook RSA after that (ie. no randomized padding - this method should not be used in real world applications) do the following:
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_NONE);
$rsa->encrypt('...');
Upvotes: 2