Skip to content

Instantly share code, notes, and snippets.

@fajarlabs
Last active October 10, 2017 17:24
Show Gist options
  • Save fajarlabs/d6dcd7cb09433c2d54c7 to your computer and use it in GitHub Desktop.
Save fajarlabs/d6dcd7cb09433c2d54c7 to your computer and use it in GitHub Desktop.
RSA Security For Java Servlet
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.StringReader;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.openssl.PEMReader;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
// References
// http://stackoverflow.com/questions/12471999/rsa-encryption-decryption-in-android
// http://stackoverflow.com/questions/15639442/encryption-php-decryption-java
// http://stackoverflow.com/questions/14516475/java-security-nosuchproviderexception-no-such-provider-bc
// http://www.massapi.com/class/se/SealedObject-3.html
public class RSASecurity {
/**
* Encode
*
* @param myMessage
* @return
*/
public static Map<String, Object> encode(String myMessage) {
// Provider first
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// Create key pair
KeyPairGenerator kpg = null;
KeyPair myPair = null;
Cipher c = null;
byte[] plainText = null;
try {
// Create RSA Intance
kpg = KeyPairGenerator.getInstance("RSA");
// Using RSA/None/OAEPWithSHA1AndMGF1Padding, BC
c = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
// using 1024
kpg.initialize(1024);
// Create keypair
myPair = kpg.genKeyPair();
// Mode encrypt
c.init(Cipher.ENCRYPT_MODE, myPair.getPublic());
// Encrypt
plainText = c.doFinal(myMessage.getBytes());
} catch (NoSuchAlgorithmException | InvalidKeyException
| IllegalBlockSizeException | NoSuchPaddingException
| NoSuchProviderException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Decoder base64
BASE64Encoder decoder = new BASE64Encoder();
// Create private key
String privateKey = "";
privateKey += "-----BEGIN RSA PRIVATE KEY-----\n";
privateKey += decoder.encode(myPair.getPrivate().getEncoded()) + "\n";
privateKey += "-----END RSA PRIVATE KEY-----";
// Create public key
String publicKey = "";
publicKey += "-----BEGIN RSA PUBLIC KEY-----\n";
publicKey += decoder.encode(myPair.getPublic().getEncoded()) + "\n";
publicKey += "-----END RSA PUBLIC KEY-----";
// Create cipherText
String cipherText = decoder.encode(plainText);
// Encrypt to base64
String privateKeyBase64 = decoder.encode(privateKey.getBytes());
String publicKeyBase64 = decoder.encode(publicKey.getBytes());
// Result
Map<String, Object> result = new HashMap<String, Object>();
result.put("cipherText", cipherText);
result.put("publicKeyBase64", publicKeyBase64);
result.put("privateKeyBase64", privateKeyBase64);
return result;
}
/**
* Decode
*
* @param b64EncryptedStr
* @param b64PrivateKey
* @return
*/
public static String decode(String b64EncryptedStr, String b64PrivateKey) {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String result = null;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Debug
// System.out.println("PrivateKey (b64): " + b64PrivateKey);
// System.out.println("Encrypted (b64): " + b64EncryptedStr);
byte[] decodedKey = decoder.decodeBuffer(b64PrivateKey);
byte[] decodedStr = decoder.decodeBuffer(b64EncryptedStr);
String decodedPrivKey = new String(decodedKey);
String decodedParsePriveKey = decodedPrivKey.replace("-----BEGIN RSA PRIVATE KEY-----\n","");
decodedParsePriveKey = decodedParsePriveKey.replace("-----END RSA PRIVATE KEY-----","");
// Decode final rsa private key
byte[] decodeFinalPrivateKey = decoder.decodeBuffer(decodedParsePriveKey);
// Using PKCS and no padding
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodeFinalPrivateKey);
// Create key factory instance
KeyFactory kf = KeyFactory.getInstance("RSA");
// Generate key factory
PrivateKey privateKey = kf.generatePrivate(keySpec);
// Cipher instance
Cipher cipher = Cipher.getInstance(
"RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
// Decrypt mode
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// Decrypt
byte[] plainText = cipher.doFinal(decodedStr);
// Convert to String
result = new String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment