Skip to content

Instantly share code, notes, and snippets.

@himanshuvirmani
Last active August 29, 2015 13:59
Show Gist options
  • Select an option

  • Save himanshuvirmani/10532236 to your computer and use it in GitHub Desktop.

Select an option

Save himanshuvirmani/10532236 to your computer and use it in GitHub Desktop.

Revisions

  1. himanshuvirmani revised this gist Apr 12, 2014. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions AESUtils.java
    Original file line number Diff line number Diff line change
    @@ -5,8 +5,9 @@
    import android.util.Base64;

    public class AESUtils {

    private AESUtils() {}

    private AESUtils() {
    }

    public static String encrypt(String key, String toEncrypt) throws Exception {
    byte[] keyBytes = key.getBytes("UTF-8");
  2. himanshuvirmani created this gist Apr 12, 2014.
    40 changes: 40 additions & 0 deletions AESUtils.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    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);
    }

    }