-
-
Save sandi2382/9b116c40515f8cb87182ae116eab76c8 to your computer and use it in GitHub Desktop.
RSA Encrypt in PHP and Decrypt in Java (Android)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
---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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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