Last active
August 29, 2015 13:59
-
-
Save himanshuvirmani/10532236 to your computer and use it in GitHub Desktop.
Simple AES encryption decryption
This file contains hidden or 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
import java.security.Key; | |
import javax.crypto.Cipher; | |
import javax.crypto.spec.SecretKeySpec; | |
import android.util.Base64; | |
public class AESUtils { | |
private AESUtils() { | |
} | |
public static String encrypt(String key, String toEncrypt) throws Exception { | |
byte[] keyBytes = key.getBytes("UTF-8"); | |
// Use the first 16 bytes (or even less if key is shorter) | |
byte[] keyBytes16 = new byte[16]; | |
System.arraycopy(keyBytes, 0, keyBytes16, 0, | |
Math.min(keyBytes.length, 16)); | |
Key skeySpec = new SecretKeySpec(keyBytes16, "AES"); | |
Cipher cipher = Cipher.getInstance("AES"); | |
cipher.init(Cipher.ENCRYPT_MODE, skeySpec); | |
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes()); | |
byte[] encryptedValue = Base64.encode(encrypted, Base64.DEFAULT); | |
return new String(encryptedValue); | |
} | |
public static String decrypt(String key, String encrypted) throws Exception { | |
byte[] keyBytes = key.getBytes("UTF-8"); | |
// Use the first 16 bytes (or even less if key is shorter) | |
byte[] keyBytes16 = new byte[16]; | |
System.arraycopy(keyBytes, 0, keyBytes16, 0, | |
Math.min(keyBytes.length, 16)); | |
Key skeySpec = new SecretKeySpec(keyBytes16, "AES"); | |
Cipher cipher = Cipher.getInstance("AES"); | |
cipher.init(Cipher.DECRYPT_MODE, skeySpec); | |
byte[] decodedBytes = Base64.decode(encrypted.getBytes(), | |
Base64.DEFAULT); | |
byte[] original = cipher.doFinal(decodedBytes); | |
return new String(original); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment