Saturday, 8 November 2014

How to encrypt strings using AES - Android/Java

Keeping your user's personal information safe is extremely important and sometimes you need to encrypt and store short strings (like user name and password) in the users's device or personal account.

The class Cypher provides various encryption algorithms and AES becoming very much a standard over 3DES.

The helper class FreeCryptoHelper is simple, ready to use and to be modified to your needs.

Pass your encryption key as an array of bytes to the constructor of the class. Read the comments in the code, keeping your key safe is extremely important. Also the length of the array must be observed or you will get an exception trying to create the key spec.

Call encryptString to encrypt a string and its counterpart decryptString to decrypt it.

Feel free to drop a comment if you have questions or suggestions.

Note that I'm using the Base64 class present in the android SDK. If you want to use pure java, checkout the Java class documentation
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;

public class FreeCryptoHelper {
  
 private SecretKeySpec mKeySpec;
 
 public FreeCryptoHelper(byte[] encryptionKey){
  // make sure encryptionKey is either 32, 64 or 128 bits long
  // and if you intend to hardcode it, have it well obfuscated within your code 
  mKeySpec = new SecretKeySpec(encryptionKey, "AES");
 }
 
 public String encryptString(String clearText) throws InvalidKeyException, NoSuchAlgorithmException, 
                NoSuchPaddingException, IllegalBlockSizeException, 
                BadPaddingException{
  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(Cipher.ENCRYPT_MODE, mKeySpec);
  byte[] encData = cipher.doFinal(clearText.getBytes());
  
  return Base64.encodeToString(encData, Base64.DEFAULT);
 }

 public String decryptString(String encryptedText) throws InvalidKeyException, 
                NoSuchAlgorithmException, NoSuchPaddingException, 
                IllegalBlockSizeException, BadPaddingException{
  byte[] encData = Base64.decode(encryptedText, Base64.DEFAULT);
  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(Cipher.DECRYPT_MODE, mKeySpec);
  byte[] decData = cipher.doFinal(encData);
  
  return new String(decData);
 }
}

No comments:

Post a Comment