Skip to content

Instantly share code, notes, and snippets.

@sandi2382
Forked from thedumbtechguy/Decrypt.java
Created April 19, 2018 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandi2382/9b116c40515f8cb87182ae116eab76c8 to your computer and use it in GitHub Desktop.
Save sandi2382/9b116c40515f8cb87182ae116eab76c8 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment