Encrypt String in PHP and Decrypt in JAVA Sample Example Tutorial

By | February 19, 2017

In this tutorial, We will learn about how to encrypt a string data using RSA algorithm through PHP and decrypt the same using Java project.

We need phpseclib library for encrypting the data. This can be downloaded from :

https://github.com/phpseclib/phpseclib/tree/master/phpseclib

Now lets create php scripts to encrypt a simple string “Hello World!”.

We need two .php files for this :

  1. keypair.php – for generating public key & private key required by RSA Algorithm for encryption.
  2. encrypt.php – for encrypting the string “Hello world!”.

Now copy the below code into keypair.php:

<?php

set_time_limit(0);
if( file_exists('private.key') )
{
    echo base64_encode(file_get_contents('private.key'));
}
else
{
    include('Crypt/RSA.php');

    $rsa = new Crypt_RSA();
    $rsa->setHash('sha1');
    $rsa->setMGFHash('sha1');
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
    $rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
    $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);

    $res = $rsa->createKey(1024);

    $privateKey = $res['privatekey'];
    $publicKey  = $res['publickey'];

    file_put_contents('public.key', $publicKey);
    file_put_contents('private.key', $privateKey);

    echo base64_encode($privateKey);
}

?>

And the code for encrypt.php is as follows:

<?php
    include('Crypt/RSA.php');
    set_time_limit(0);

    $rsa = new Crypt_RSA();
    $rsa->setHash('sha1');
    $rsa->setMGFHash('sha1');
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);

    $rsa->loadKey(file_get_contents('public.key')); // public key

    $plaintext  = 'Hello World!';
    $ciphertext = $rsa->encrypt($plaintext);
    $md5        = md5($ciphertext);
    file_put_contents('md5.txt', $md5);
    file_put_contents('encrypted.txt', base64_encode($ciphertext));

    echo base64_encode($ciphertext);

?>

NOTE: If there is an error on include statement, Simply copy the whole directory structure with files from phpseclib library to resolve: include(‘Crypt/RSA.php’)

Now we are done for the (server side) PHP part of code.

I am using cpanel on a hosting platform and my project structure for php side is as follows:

string encrypt php & java

string encrypt php & java

Now lets work on the Java Part:

We need two libraries for our java project to decrypt the string we encrypt in encrypt.php:

  1. bcprov.jar
  2. sun.misc.BASE64Decoder.jar

Download this zip which contains both these files: libs

Create a new java project in Eclipse (I have used eclipse IDE for this java project).  Now extract the libs.zip and copy the libs folder in root directory of your java project. Add both the jar files to build path of your java project.

 

Now create a new file Main.java with following code:

package testEncryption;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.StringReader;
import java.net.URL;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.Security;

import javax.crypto.Cipher;

import org.bouncycastle.openssl.PEMReader;

import Decoder.BASE64Decoder;


public class Main {

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        try {
            BASE64Decoder decoder   = new BASE64Decoder();
            
            String b64PrivateKey    = getContents("http://www.yourdoamin.com/pathto/keypair.php").trim();
            String b64EncryptedStr  = getContents("http://www.yourdoamin.com/pathto/encrypt.php").trim();
         
            System.out.println("PrivateKey (b64): " + b64PrivateKey);
            System.out.println(" Encrypted (b64): " + b64EncryptedStr);

            byte[] decodedKey           = decoder.decodeBuffer(b64PrivateKey);
            byte[] decodedStr           = decoder.decodeBuffer(b64EncryptedStr);
            PrivateKey privateKey       = strToPrivateKey(new String(decodedKey));

            Cipher cipher               = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);


            byte[] plainText            = cipher.doFinal(decodedStr);

            System.out.println("         Message: " + new String(plainText));
        }
        catch( Exception e )
        {
            System.out.println("           Error: " + e.getMessage());
        }

    }

    public static String getContents(String url)
    {
        try {
            String result = "";
            String line;
            URL u = new URL(url);
            DataInputStream theHTML = new DataInputStream(u.openStream());
            while ((line = theHTML.readLine()) != null)
                result = result + "\n" + line;

            return result;
        }
        catch(Exception e){}

        return "";
    }

    public static PrivateKey strToPrivateKey(String s)
    {
        try {
            BufferedReader br   = new BufferedReader( new StringReader(s) );
            PEMReader pr        = new PEMReader(br);
            KeyPair kp          = (KeyPair)pr.readObject();
            pr.close();
            return kp.getPrivate();
        }
        catch( Exception e )
        {

        }

        return null;
    }
}

NOTE: Please provide the URLs for the PHP files we just created in this tutorial in Main.java file.

My project structure for java project:
rsa decryption java

Now the Main.java file as Java Application and you will see that
hello world!
is printed on the console!

We have successfully encrypted and decrypted the string between PHP and JAVA!

1,553 total views, 7 views today

(Visited 861 times, 6 visits today)