Good example of using RSA in php

I am trying to figure out a way to use RSA in php.

I created public and private keys with

ssh-keygen -t rsa 

And now I'm trying to use them from my php code. Here is the code I'm using:

 <?php $string=$_GET["i"]; //$fp=fopen ("public.pem","r"); $pub_key='ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAtTLDrnS+MyPb/MGHzgcS90DgaoPiDNattlL0Xo7keAjfqz5/yCXU0L8ilkAWIwME5DdXK04MskRtupYPwxPGB4Y7bG/4wvArx5FEgDSq6FUMNvQZ/Vqj13uvcjadLctC2ypAUPRo39qO1IGLEDEWNOS49UgLxzfnr1dZF/Ox5m5UjhOjsALcTiv4eR6ClGcCrAHE7Jp5nL2BwVu46nx3eFlpe7cljQVUOQDgUa5yWaRoJE6qcYgQu1TDo6b/pcAWU1WVu+HzJY4g0aoV2VqamCnl3oyWoPz7ykvxbJbHv7/qTbV+IBNzSx4R7KSppvnPKsrbeiWROvZ4JF84leX+Iw== root@ip-10-83-11-72 '; //fclose($fp); $PK=""; $PK=openssl_get_publickey($pub_key); if (!$PK) { echo "Cannot get public key"; echo $pub_key; } $finaltext=""; openssl_public_encrypt($string,$finaltext,$PK); if (!empty($finaltext)) { openssl_free_key($PK); echo "Encryption OK!"; echo $finaltext; echo "<br/><br/><br/>"; }else{ echo "Cannot Encrypt"; } // STEP 2: Decription (Using Private Key) //$fp=fopen ("private.pem","r"); $priv_key2='-----BEGIN RSA PRIVATE KEY----- MIIEoAIBAAKCAQEAtTLDrnS+MyPb/MGHzgcS90DgaoPiDNattlL0Xo7keAjfqz5/ yCXU0L8ilkAWIwME5DdXK04MskRtupYPwxPGB4Y7bG/4wvArx5FEgDSq6FUMNvQZ /Vqj13uvcjadLctC2ypAUPRo39qO1IGLEDEWNOS49UgLxzfnr1dZF/Ox5m5UjhOj sALcTiv4eR6ClGcCrAHE7Jp5nL2BwVu46nx3eFlpe7cljQVUOQDgUa5yWaRoJE6q cYgQu1TDo6b/pcAWU1WVu+HzJY4g0aoV2VqamCnl3oyWoPz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C0bpwkfbE97AtQoPW5DnLRVQI9uanJiiix1PvHr iQKBgBj/RiXsDHvVJ28xZPUffZntrAD/TWXMHZWVMFgfsf8Ti0O7ypXqY43+Aoph nfDH6xJFqU9azsiv5xQVY7X1h4+DuOamqdawIV5LtYod+ip0dxduQMfrqLld/p0m E+jAaxvC4b6zqomFnZ9MB9eAzUg9i8UQkc4H3cH/bO6MKPG3 -----END RSA PRIVATE KEY----- ';//fread ($fp,8192); //fclose($fp); $PK2=openssl_get_privatekey($priv_key2); $Crypted=openssl_private_decrypt($Data,$Decrypted,$PK2); if (!$Crypted) { $MSG.="<p class='error'>Cannot Decrypt ($CCID).</p>"; }else{ echo "Decrypted Data: " . $Decrypted; } 

At the end, the application crashes:

 Cannot get public key Warning: openssl_public_encrypt() [function.openssl-public-encrypt]: key parameter is not a valid public key in /home/menkaur/public_html/iathao.com/bookmarks/lcn.php on line 13 Cannot Encrypt 

what am I doing wrong?

+4
source share
1 answer

The key that openssl uses is in PEM format. To generate it, use the following code:

 openssl genrsa -des3 -out private.pem 1024 

It will generate a file called private.pem. Then you can generate the public key using:

 openssl rsa -in private.pem -out public.pem -outform PEM -pubout 

In PHP, you can use these keys as follows:

 <?php $pub = file_get_contents('public.pem'); $pk = openssl_get_publickey($pub); if(!$pk) ... 

Then use your logic to do whatever you want.

+7
source

All Articles