This article shows you one way to get RSA encryption working between Java and PHP without any extra libraries or classes, you only need the openssl module activated on PHP side.
The goal is to encrypt a text with a public key in Java and send the code to PHP where it is decoded with the private key.
It took me two days and a lot of googling to figure this out, and I hope this will help others not to spend so much time on this topic.
1) Install and Configure PHP OpenSSL (Windows)
- php.ini: extension=php_openssl.dll
- Set environment variable
OPENSSL_CONF to C:\Programme\Apache2.2\php\extras\openssl\openssl.cnf - Set environment variable
PATH to C:\Programme\Apache2.2\php
2) Generate a private keyfile with PHP
1
2
3
| $keys = openssl_pkey_new(); $priv = openssl_pkey_get_private( $keys ); openssl_pkey_export_to_file( $priv , 'private.pem' ); |
3) Generate a public .der-file from the private keyfile with OpenSSL
- openssl rsa -in private.pem -pubout -outform DER -out public.der
4) Import the public key in Java
1
2
3
4
5
6
7
8
9
10
| File pubKeyFile = new File( "public.der" ); DataInputStream dis = new DataInputStream( new FileInputStream(pubKeyFile)); byte [] keyBytes = new byte [( int ) pubKeyFile.length()]; dis.readFully(keyBytes); dis.close(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance( "RSA" ); RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec); |
5) Encode the data in Java with the public key
1
2
3
| Cipher cipher = Cipher.getInstance( "RSA/ECB/PKCS1PADDING" ); cipher.init(Cipher.ENCRYPT_MODE, publicKey); encrypted = cipher.doFinal(text.getBytes()); |
6) Decode the data with the private key in PHP
$fp = fopen(“private.pem”, “r”);
$privateKey = fread($fp, 8192);
fclose($fp);
$privateKey = fread($fp, 8192);
fclose($fp);
$res = openssl_get_privatekey($privateKey);
openssl_private_decrypt($this->hex2bin($params[‘cipher’]), $decrypted, $res);
openssl_private_decrypt($this->hex2bin($params[‘cipher’]), $decrypted, $res);
// $decrypted is the result
function hex2bin($hexdata) {
$bindata = “”;
$bindata = “”;
for ($i = 0; $i < strlen($hexdata); $i += 2) { $bindata .= chr(hexdec(substr($hexdata, $i, 2))); } return $bindata; } [/sourcecode] 7) If you want to decrypt with the public key in PHP as well, you can generate a public.pem file with OpenSSL
- openssl rsa -in private.pem -out public.pem -outform PEM -puboutr
Original Post URL: https://schneimi.wordpress.com/2008/11/25/rsa-encryption-between-java-and-php/
No comments:
Post a Comment