Send and receive encrypted data between PHP and JAVA. part 2

previous post: Send and receive encrypted data between PHP and JAVA. part 1

Part2. Using public and private key to encrypt and decrypt data

Encrypt Decrypt using public and private key is called Asynchronus Encryption, which mean the key used to encrypt is different from the key used to decrypt, but both keys must be a pairs so they match to each other.
The point is, when we encrypt a message using a private key, so we only can decrypt that message with its public key, and when we encrypt a message using a public key, so we only can decrypt that message with its private key.
To create a private key and public key you can read my other article Common SSL Commands

Encrypt message using Private Key and then Decrypt it using Public Key (JAVA)

Encrypt a message using Private Key

//-------------------- Get the private key (DER format) --------------------
KeyFactory keyFactory;
PrivateKey privateKey = null;
File privKeyFile = new File("/path_to/privatekey.der");

// read private key DER file
DataInputStream dis;
try {
    dis = new DataInputStream(new FileInputStream(privKeyFile));
    byte[] privKeyBytes = new byte[(int) privKeyFile.length()];
    dis.read(privKeyBytes);
    dis.close();
    keyFactory = KeyFactory.getInstance("RSA");
    // decode private key
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
    privateKey = (PrivateKey) keyFactory.generatePrivate(privSpec);
} catch (Exception e) {
    e.printStackTrace();
}

// -------------------- Encryption using the private key --------------------
BASE64Encoder encoder = new BASE64Encoder();
Cipher privateChiper = null;
byte[] encrypted = null;
String encryptedText = null;
String plaintext =  "This is the message that we want to encrypt with private key on java";
try {
    privateChiper = Cipher.getInstance("RSA");
    privateChiper.init(Cipher.ENCRYPT_MODE, privateKey);
    encrypted =  privateChiper.doFinal(plaintext.getBytes());
    encryptedText = encoder.encode(encrypted);
} catch (Exception e) {
    e.printStackTrace();
}

System.out.println(encryptedText);
//output:
//HNDERrUmko0gqwzeW4XUWIIeds8FaW0eKH9qO4DkI7eq2DSPBCKjnxsggSBvTU4AHtroOrVbl39M42tJFjRHN19iG7osda4Y0vWBNlPnsSxfSLipeypMIktqbIQnl5uarZXtqi/PDQNzC7HNTns508fXHax8cLIqE6J6aWmsD9M=

Decrypt the encrypted message from above script using Public Key

// -------------------- Get the public key --------------------
BASE64Decoder decoder = new BASE64Decoder();
FileInputStream is;
CertificateFactory cf;
PublicKey publicKey = null;
try {
    is = new FileInputStream("/path_to/publickey.crt");
    cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(is);
    publicKey = cert.getPublicKey();
} catch (Exception e) {
    e.printStackTrace();
} 

// -------------------- Decryption using the public key --------------------
Cipher publicChiper = null;
String decryptedText = null;
String cryptedText = "HNDERrUmko0gqwzeW4XUWIIeds8FaW0eKH9qO4DkI7eq2DSPBCKjnxsggSBvTU4AHtroOrVbl39M42tJFjRHN19iG7osda4Y0vWBNlPnsSxfSLipeypMIktqbIQnl5uarZXtqi/PDQNzC7HNTns508fXHax8cLIqE6J6aWmsD9M=";
try {
    publicChiper = Cipher.getInstance("RSA");
    publicChiper.init(Cipher.DECRYPT_MODE, publicKey);
    byte[] decodedMessage = decoder.decodeBuffer(cryptedText);
    byte[] decrypted = publicChiper.doFinal(decodedMessage);
    decryptedText =  new String(decrypted);
} catch (Exception e) {
    e.printStackTrace();
}

System.out.println(decryptedText);
// output: This is the message that we want to encrypt with private key on java

 

Encrypt message using Public Key and then Decrypt it using Private Key (JAVA)

Encrypt a message using Public Key

// -------------------- Get the public key --------------------
FileInputStream is;
CertificateFactory cf;
PublicKey publicKey = null;
try {
    is = new FileInputStream("/path_to/publickey.crt");
    cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(is);
    publicKey = cert.getPublicKey();
} catch (Exception e) {
    e.printStackTrace();
} 

// -------------------- Encryption using the public key --------------------
BASE64Encoder encoder = new BASE64Encoder();
Cipher publicChiper = null;
byte[] encrypted = null;
String encryptedText = null;
String plaintext =  "This is the message that we want to encrypt with public key on java";
try {
    publicChiper = Cipher.getInstance("RSA");
    publicChiper.init(Cipher.ENCRYPT_MODE, publicKey);
    encrypted =  publicChiper.doFinal(plaintext.getBytes());
    encryptedText = encoder.encode(encrypted);
} catch (Exception e) {
    e.printStackTrace();
}
System.out.println(encryptedText);
//output:
//EFB5fOc0vP30+v3lIHrtuuNgyWu+4tYjLBBN4VEY+YPqMGA4CM+jJLfXfSHbWXUEacQ5KsVzliQLh5GB/u14qmNBqlE5WlhY8XMdCW3jbXo6NFk89cPE2HveRVeIQNb5UU7ogBwcBcvR2scmqcBzbP6Z2Ixf0NFjQWEpwOwj+bw=

Decrypt the encrypted message from above script using Private Key

//-------------------- Get the private key (DER format) --------------------
KeyFactory keyFactory;
PrivateKey privateKey = null;
File privKeyFile = new File("/path_to/privatekey.der");

// read private key DER file
DataInputStream dis;
try {
    dis = new DataInputStream(new FileInputStream(privKeyFile));
    byte[] privKeyBytes = new byte[(int) privKeyFile.length()];
    dis.read(privKeyBytes);
    dis.close();
    keyFactory = KeyFactory.getInstance("RSA");
    // decode private key
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
    privateKey = (PrivateKey) keyFactory.generatePrivate(privSpec);
} catch (Exception e) {
    e.printStackTrace();
}

// -------------------- Decryption using the private key --------------------
BASE64Decoder decoder = new BASE64Decoder();
Cipher privateChiper = null;
String decryptedText = null;
String cryptedText = "EFB5fOc0vP30+v3lIHrtuuNgyWu+4tYjLBBN4VEY+YPqMGA4CM+jJLfXfSHbWXUEacQ5KsVzliQLh5GB/u14qmNBqlE5WlhY8XMdCW3jbXo6NFk89cPE2HveRVeIQNb5UU7ogBwcBcvR2scmqcBzbP6Z2Ixf0NFjQWEpwOwj+bw=";
try {
    privateChiper = Cipher.getInstance("RSA");
    privateChiper.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] decodedMessage = decoder.decodeBuffer(cryptedText);
    byte[] decrypted = privateChiper.doFinal(decodedMessage);
    decryptedText =  new String(decrypted);
} catch (Exception e) {
    e.printStackTrace();
}

System.out.println(decryptedText);
// output: This is the message that we want to encrypt with public key on java

 

Encrypt message using Private Key and then Decrypt it using Public Key (PHP)

Encrypt a message using Private Key

// Get the private key
$private_key_file = "/path_to/privatekey.key";
$private_key_passphrase = "the_key_pasphrase";
$handle = fopen($private_key_file, "r");
$content = fread($handle, filesize($private_key_file));
fclose($handle);
$privateKey = openssl_get_privatekey($content, $private_key_passphrase);

// Encrypt message with private key
$plaintext = "This is the message that we want to encrypt with private key on php";
$encryptedText = "";
if (openssl_private_encrypt($plaintext, $cryptedMessage, $privateKey)){
	$encryptedText = base64_encode($cryptedMessage);
	echo $encryptedText;
	// output: SFWPsRitclLqRAB/mf3w7FwhJgN0ASiKioiNwOM3DGzkvZx+rWN6j0DaAFDue1iUJY+t1uUlpOVm1qctaHYQeRx+C2wnr1B75CUO5mvsrr7FTCJivuwAErCxGZubaIQNmq+MnAqAF52AA9st3Ri8OtrMISV5/ODcpOOLQKlBZvs=
} else {
	echo "cannot encrypt the message using private key";
}

Decrypt the encrypted message from above script using Public Key (PHP)

// Get the public key
$public_key_file = "/path_to/publickey.crt";
$handle = fopen ($public_key_file, "r");
$content = fread($handle, filesize($public_key_file));
fclose($handle);
$publicKey = openssl_get_publickey($content);

// Decrypt the message using public key
$cryptedText = "SFWPsRitclLqRAB/mf3w7FwhJgN0ASiKioiNwOM3DGzkvZx+rWN6j0DaAFDue1iUJY+t1uUlpOVm1qctaHYQeRx+C2wnr1B75CUO5mvsrr7FTCJivuwAErCxGZubaIQNmq+MnAqAF52AA9st3Ri8OtrMISV5/ODcpOOLQKlBZvs=";
$decodedText = base64_decode($cryptedText);
$decryptedText = "";
if (openssl_public_decrypt($decodedText, $decryptedText, $publicKey)){
	echo $decryptedText;
} else {
	echo "cannot decrypt the message using public key";
}

 

Encrypt message using Public Key and then Decrypt it using Private Key (PHP)

Encrypt a message using Public Key

// Get the public key
$public_key_file = "/path_to/publickey.crt";
$handle = fopen ($public_key_file, "r");
$content = fread($handle, filesize($public_key_file));
fclose($handle);
$publicKey = openssl_get_publickey($content);

// Encrypt the message using public key
$plaintext = "This is the message that we want to encrypt with public key on php";
$encryptedText = "";
if (openssl_public_encrypt($plaintext, $cryptedMessage, $publicKey)){
	$encryptedText = base64_encode($cryptedMessage);
	echo $encryptedText;
	// output: TiwOZrKmlPVvGy97TUA7i4kxnSgD+VTWIiklTuIaJqeQjDHqwFulpJ5WDdXh1vrj+AJQXlGfa1EH/BnMCBVeabP2jTEpivWJhNqXn+M0oma7ytXEjGAeg8FHszntN7P/RY4wqLWQj1sbKCgtUjjO8FWK9xCYRQbqc27vvgwKwPI=
}else{
	echo "cannot encrypt the message using public key";
}

Decrypt the encrypted message from above script using Private Key (PHP)

// Get the private key
$private_key_file = "/path_to/privatekey.key";
$private_key_passphrase = "the_key_pasphrase";
$handle = fopen($private_key_file, "r");
$content = fread($handle, filesize($private_key_file));
fclose($handle);
$privateKey = openssl_get_privatekey($content, $private_key_passphrase);

// Decrypt the message using private key
$cryptedText = "TiwOZrKmlPVvGy97TUA7i4kxnSgD+VTWIiklTuIaJqeQjDHqwFulpJ5WDdXh1vrj+AJQXlGfa1EH/BnMCBVeabP2jTEpivWJhNqXn+M0oma7ytXEjGAeg8FHszntN7P/RY4wqLWQj1sbKCgtUjjO8FWK9xCYRQbqc27vvgwKwPI=";
$decodedText = base64_decode($cryptedText);
$decryptedText = "";
if (openssl_private_decrypt($decodedText, $decryptedText, $privateKey)){
	echo $decryptedText;
}else{
	echo "cannot decrypt the message using private key";
}

note: all encrypted results from this code wont be the same with your result

You also can do something like this:

  • encrypt a message using Private Key in JAVA and then decrypt it using Public Key in PHP
  • encrypt a message using Private Key in PHP and then decrypt it using Public Key in JAVA
  • encrypt a message using Public Key in JAVA and then decrypt it using Private Key in PHP
  • encrypt a message using Public Key in PHP and then decrypt it using Private Key in JAVA


Similar Posts:

Bookmark:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • description
  • LinkedIn
  • Slashdot
  • Technorati
  • TwitThis
  • Yahoo! Buzz

Leave a comment

Your comment

Spam Protection by WP-SpamFree