In this article we will learn how make a program which to helps you learn how you can perform encryption/decryption with java.
In this post I explain the encryption and decryption of string using Cipher class.Below is the class in which method for encryption and decryption.
Add this class in your android project package.
import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;import android.util.Base64;public class AESHelper{public static String encrypt(String seed, String cleartext) throws Exception {byte[] rawKey = seed.getBytes();byte[] result = encrypt(rawKey, cleartext.getBytes());return Base64.encodeToString(result, Base64.DEFAULT);}public static String decrypt(String seed, String encrypted) throws Exception {byte[] rawKey = seed.getBytes();byte[] enc = Base64.decode(encrypted, Base64.DEFAULT);byte[] result = decrypt(rawKey, enc);return new String(result);}private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.ENCRYPT_MODE, skeySpec);byte[] encrypted = cipher.doFinal(clear);return encrypted;}private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");cipher.init(Cipher.DECRYPT_MODE, skeySpec);byte[] decrypted = cipher.doFinal(encrypted);return decrypted;}}
For encryption of the string using this class
AESHelper.encrypt(HERE IS YOUR ENCRYPTION KEY, HERE PASS YOUR STRING TO BE ENCRYPT);For decryption of the string using above class
AESHelper.decrypt(HERE IS YOUR ENCRYPTION KEY, HERE PASS YOUR STRING TO BE DECRYPT);NOTE : Make sure that your key is of 128 bit or higher.
Hope this post is helpful for you...
No comments:
Post a Comment