Skip to content

Instantly share code, notes, and snippets.

@priyankahdp
Last active January 26, 2017 12:40
Show Gist options
  • Save priyankahdp/744b4c8ab160357691f470467b0b17ba to your computer and use it in GitHub Desktop.
Save priyankahdp/744b4c8ab160357691f470467b0b17ba to your computer and use it in GitHub Desktop.
RSA Encryption Decryption Class Demo
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class RSAEncDecDemo {
private static final String PUBLIC_KEY_FILE = "lk.public.key";
private static final String PRIVATE_KEY_FILE = "lk.private.key";
@SuppressWarnings("restriction")
public static void main(String[] args) throws IOException {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
writeStringkey(PUBLIC_KEY_FILE,new BASE64Encoder().encode(publicKey.getEncoded()));
writeStringkey(PRIVATE_KEY_FILE,new BASE64Encoder().encode(privateKey.getEncoded()));
String demoString = "735e558310552d82269bb1afe8bbfd55516d6bf9a582020bb065b3be22ca170e15a446c38bcbe856d0a6ae537b93c336fd8133ac930fe67d404590899f1c6424ecfd1466a5134262e32a13867106c0d455f357df1285506cb350bd74edeb75395678d6d7bbad7bc0eb32fc7fbba15fabf5bb7419312ff8f3c47f4d3358aabe27eace53744d209df884ba93d85f5fb8d6e6a706e56f6b1092699eea34560f0c465512d5e6d049a9aa4454dbf7e96367a9a801a7421d526acbbba49a1b46cbd126d3200b309decb2b5fa09ad16aa11d155f021989e3f8316d3bf20d13fc59498eaa2977dbe6f64c5fb601f04dd70bfaae4f7b85b3369893a054cfe23fbef066090";
RSAEncDecDemo rsa = new RSAEncDecDemo();
String decrypted = rsa.decryptData(demoString);
String msisdn = decrypted.substring(0,decrypted.indexOf("|"));
} catch (Exception e) {
e.printStackTrace();
}
}
private String decryptData(String strData) throws IOException {
byte[] data = DatatypeConverter.parseHexBinary(strData);
byte[] descryptedData = null;
try {
PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
descryptedData = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return new String(descryptedData);
}
@SuppressWarnings("restriction")
public PrivateKey readPrivateKeyFromFile(String fileName)throws IOException, NoSuchAlgorithmException,InvalidKeySpecException {
String publicK = readStringKey(fileName);
byte[] keyBytes = new BASE64Decoder().decodeBuffer(publicK);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePrivate(keySpec);
}
public PrivateKey readPrivateKeyFromFileold(String fileName)throws IOException {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
return privateKey;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
ois.close();
if (fis != null) {
fis.close();
}
}
}
return null;
}
public static void writeStringkey(String fileName, String data) {
try {
FileWriter out = new FileWriter(new File(fileName));
out.write(data);
out.close();
} catch (IOException e) {
}
}
public static String readStringKey(String fileName) {
BufferedReader reader = null;
StringBuffer fileData = null;
try {
fileData = new StringBuffer(2048);
reader = new BufferedReader(new FileReader(fileName));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
} catch (Exception e) {
} finally {
if (reader != null) {
reader = null;
}
}
return fileData.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment