Skip to content

Instantly share code, notes, and snippets.

@thedumbtechguy
Last active December 1, 2018 21:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save thedumbtechguy/c17e6c3b2098a9c5d04d to your computer and use it in GitHub Desktop.
Save thedumbtechguy/c17e6c3b2098a9c5d04d to your computer and use it in GitHub Desktop.
RSA Encrypt in PHP and Decrypt in Java (Android)
---Java
//I used this on Android
//before you proceed, you need to ensure your private key is PKCS8 since that is what can be read natively in java.
//If your key begins with -----BEGIN RSA PRIVATE KEY-----, the it is ssleay and you need to convert it using the openssl command below
//openssl pkcs8 -topk8 -inform pem -in ssleay-private-key.key -outform pem -nocrypt -out pkcs8-private-key.pem
final private static String RSA_PRIVATE_KEY =
"-----BEGIN PRIVATE KEY-----\n" +
"MI...\n" +
"2...\n" +
"HPt...\n" +
...
"v3...\n" +
"-----END PRIVATE KEY-----";
public static byte[] decrypt(String key) throws Exception {
String privKeyPEM = RSA_PRIVATE_KEY.replace("-----BEGIN PRIVATE KEY-----\n", "");
privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
byte [] encoded = Base64.decode(privKeyPEM, Base64.DEFAULT);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] decodedStr = Base64.decode(key, Base64.DEFAULT);
byte[] plainText = cipher.doFinal(decodedStr);
return plainText;
}
<?php
function encrypt($string)
{
$key =
"-----BEGIN PUBLIC KEY-----
MIGfM....
gUn....
7eMl....
yXd....
-----END PUBLIC KEY-----";
openssl_public_encrypt($string, $crypted, $key);
return base64_encode($crypted);
}
@aryanduntley
Copy link

Would you happen to have the reversal methods? decrypt in php, encrypt in java?

@tarekch
Copy link

tarekch commented May 4, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment