AES decrypt byte array content - Android java.security

Android examples for java.security:AES

Description

AES decrypt byte array content

Demo Code

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Main {

  public static byte[] decrypt(byte[] content, String password) throws java.security.InvalidKeyException {
    try {/*w  ww . ja  v a  2s . com*/
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(128, new SecureRandom(password.getBytes()));
      SecretKey secretKey = kgen.generateKey();
      byte[] enCodeFormat = secretKey.getEncoded();
      SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, key);
      byte[] result = cipher.doFinal(content);
      return result;

    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

}

Related Tutorials