Requirements
In order to keep this script as simple as possible you will need php’s gmp extension.This will help you to handle big numbers.
Algorithm
The most important/hard part of this algorithm is getting the public and private keys. And for this all we need is to “translate” the steps you can find in that wikipedia article to php. I won’t even bore you with this here, you will find the function called get_rsa_keys inside a full working example available for download at the end of this post.You will also need another function to get the modular multiplicative inverse of a number. I must say that I got the function from the same wikipedia some time ago (it’s not available now for some reason) and changed it a bit as it had a bug.
This other function will also be available in the code provided and it will have the name modinverse.
RSA Encryption
This will be very easy. After you will have the needed keys (public and private) anyone that knows the public key can use it to encrypt a secret using this function:
1
2
3
4
5
| function rsa_encrypt( $message , $public_key_d , $public_key_n ) { $resp = gmp_powm( $message , $public_key_d , $public_key_n ); return $resp ; } |
RSA Decryption
Now it’s your part: the guy that has the private key. Someone should have provided you an encrypted string generated using your public key and you are the only one that can decrypt this to get the original secret. You will need to use this function:
1
2
3
4
5
| function rsa_decrypt( $value , $private_key_e , $public_key_n ) { $resp = gmp_powm( $value , $private_key_e , $public_key_n ); return $resp ; } |
Usage
The typical usage for this algorithm is to generate the keys once, save the private key so that you are the only one to have access to it, and provide the public key to the people that want to send you encrypted messages (or use them in another algorithm on your application).Notice that the values returned by the get_rsa_keys are d, e, n.
- n will be part of both the public and the private key.
- Any of the two values e and d can be the other part of the keys.
For more details on the security and different usages of this algorithm check the wikipedia article.
In this full working example you will find everything you need to run this algorithm in just 80 lines. Don’t worry, only 3 of them are there for using the algorithm, you can just copy the functions in your project an call them.
The first one – getting the keys:
1
| list( $public_key_n , $public_key_d , $private_key_e ) = get_rsa_keys(); |
1
| $encrypted = rsa_encrypt( $secret , $public_key_d , $public_key_n ); |
1
| $decrypted = rsa_decrypt( $encrypted , $private_key_e , $public_key_n ); |
references: http://www.onlinesolutionsdevelopment.com/
0 comments:
Post a Comment