Last active
February 15, 2016 03:28
-
-
Save tyaslab/aed85e3b5084a5b4bbf9 to your computer and use it in GitHub Desktop.
Android Snippet - RSA
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
package in.javadigest.encryption; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.security.KeyPair; | |
import java.security.KeyPairGenerator; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.PrivateKey; | |
import java.security.PublicKey; | |
import javax.crypto.Cipher; | |
/** | |
* @author JavaDigest | |
* | |
*/ | |
public class EncryptionUtil { | |
/** | |
* String to hold name of the encryption algorithm. | |
*/ | |
public static final String ALGORITHM = "RSA"; | |
/** | |
* String to hold the name of the private key file. | |
*/ | |
public static final String PRIVATE_KEY_FILE = "C:/keys/private.key"; | |
/** | |
* String to hold name of the public key file. | |
*/ | |
public static final String PUBLIC_KEY_FILE = "C:/keys/public.key"; | |
/** | |
* Generate key which contains a pair of private and public key using 1024 | |
* bytes. Store the set of keys in Prvate.key and Public.key files. | |
* | |
* @throws NoSuchAlgorithmException | |
* @throws IOException | |
* @throws FileNotFoundException | |
*/ | |
public static void generateKey() { | |
try { | |
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM); | |
keyGen.initialize(1024); | |
final KeyPair key = keyGen.generateKeyPair(); | |
File privateKeyFile = new File(PRIVATE_KEY_FILE); | |
File publicKeyFile = new File(PUBLIC_KEY_FILE); | |
// Create files to store public and private key | |
if (privateKeyFile.getParentFile() != null) { | |
privateKeyFile.getParentFile().mkdirs(); | |
} | |
privateKeyFile.createNewFile(); | |
if (publicKeyFile.getParentFile() != null) { | |
publicKeyFile.getParentFile().mkdirs(); | |
} | |
publicKeyFile.createNewFile(); | |
// Saving the Public key in a file | |
ObjectOutputStream publicKeyOS = new ObjectOutputStream( | |
new FileOutputStream(publicKeyFile)); | |
publicKeyOS.writeObject(key.getPublic()); | |
publicKeyOS.close(); | |
// Saving the Private key in a file | |
ObjectOutputStream privateKeyOS = new ObjectOutputStream( | |
new FileOutputStream(privateKeyFile)); | |
privateKeyOS.writeObject(key.getPrivate()); | |
privateKeyOS.close(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* The method checks if the pair of public and private key has been generated. | |
* | |
* @return flag indicating if the pair of keys were generated. | |
*/ | |
public static boolean areKeysPresent() { | |
File privateKey = new File(PRIVATE_KEY_FILE); | |
File publicKey = new File(PUBLIC_KEY_FILE); | |
if (privateKey.exists() && publicKey.exists()) { | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Encrypt the plain text using public key. | |
* | |
* @param text | |
* : original plain text | |
* @param key | |
* :The public key | |
* @return Encrypted text | |
* @throws java.lang.Exception | |
*/ | |
public static byte[] encrypt(String text, PublicKey key) { | |
byte[] cipherText = null; | |
try { | |
// get an RSA cipher object and print the provider | |
final Cipher cipher = Cipher.getInstance(ALGORITHM); | |
// encrypt the plain text using the public key | |
cipher.init(Cipher.ENCRYPT_MODE, key); | |
cipherText = cipher.doFinal(text.getBytes()); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return cipherText; | |
} | |
/** | |
* Decrypt text using private key. | |
* | |
* @param text | |
* :encrypted text | |
* @param key | |
* :The private key | |
* @return plain text | |
* @throws java.lang.Exception | |
*/ | |
public static String decrypt(byte[] text, PrivateKey key) { | |
byte[] dectyptedText = null; | |
try { | |
// get an RSA cipher object and print the provider | |
final Cipher cipher = Cipher.getInstance(ALGORITHM); | |
// decrypt the text using the private key | |
cipher.init(Cipher.DECRYPT_MODE, key); | |
dectyptedText = cipher.doFinal(text); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
return new String(dectyptedText); | |
} | |
/** | |
* Test the EncryptionUtil | |
*/ | |
public static void main(String[] args) { | |
try { | |
// Check if the pair of keys are present else generate those. | |
if (!areKeysPresent()) { | |
// Method generates a pair of keys using the RSA algorithm and stores it | |
// in their respective files | |
generateKey(); | |
} | |
final String originalText = "Text to be encrypted "; | |
ObjectInputStream inputStream = null; | |
// Encrypt the string using the public key | |
inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE)); | |
final PublicKey publicKey = (PublicKey) inputStream.readObject(); | |
final byte[] cipherText = encrypt(originalText, publicKey); | |
// Decrypt the cipher text using the private key. | |
inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE)); | |
final PrivateKey privateKey = (PrivateKey) inputStream.readObject(); | |
final String plainText = decrypt(cipherText, privateKey); | |
// Printing the Original, Encrypted and Decrypted Text | |
System.out.println("Original: " + originalText); | |
System.out.println("Encrypted: " +cipherText.toString()); | |
System.out.println("Decrypted: " + plainText); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
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
public static byte[] decryptRSA(Context mContext, byte[] message) throws Exception { | |
// reads the public key stored in a file | |
InputStream is = mContext.getResources().openRawResource(R.raw.sm_public); | |
BufferedReader br = new BufferedReader(new InputStreamReader(is)); | |
List<String> lines = new ArrayList<String>(); | |
String line = null; | |
while ((line = br.readLine()) != null) | |
lines.add(line); | |
// removes the first and last lines of the file (comments) | |
if (lines.size() > 1 && lines.get(0).startsWith("-----") && lines.get(lines.size()-1).startsWith("-----")) { | |
lines.remove(0); | |
lines.remove(lines.size()-1); | |
} | |
// concats the remaining lines to a single String | |
StringBuilder sb = new StringBuilder(); | |
for (String aLine: lines) | |
sb.append(aLine); | |
String keyString = sb.toString(); | |
Log.d("log", "keyString:"+keyString); | |
// converts the String to a PublicKey instance | |
byte[] keyBytes = Base64.decodeBase64(keyString.getBytes("utf-8")); | |
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); | |
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); | |
PublicKey key = keyFactory.generatePublic(spec); | |
// decrypts the message | |
byte[] dectyptedText = null; | |
Cipher cipher = Cipher.getInstance("RSA"); | |
cipher.init(Cipher.DECRYPT_MODE, key); | |
dectyptedText = cipher.doFinal(Base64.decodeBase64(message)); | |
return dectyptedText; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment