Android AES Encrypt encryptBase64(String content, String key)

Here you can find the source of encryptBase64(String content, String key)

Description

encrypt Base

Declaration

public static String encryptBase64(String content, String key) 

Method Source Code

//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Main {
    private static final String UTF_8 = "UTF-8";
    private static final byte[] defaultIV = { 127, 24, 123, 23, 93, 7, 15,
            0, 9, 4, 8, 15, 16, 23, 42, 1 };

    public static String encryptBase64(String content, String key) {
        try {// ww  w .  j  a v a  2  s.co  m
            byte[] res = encrypt(content.getBytes(UTF_8), key);
            return new String(Base64.encodeBase64(res), UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] encrypt(byte[] content, String key) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ivs = new IvParameterSpec(defaultIV);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key), ivs);

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

    private static SecretKeySpec getSecretKey(String key) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("md5");
            SecretKeySpec keySpec = new SecretKeySpec(digest.digest(key
                    .getBytes(UTF_8)), "AES");
            return keySpec;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. encrypt(byte[] raw, byte[] clear)
  2. encrypt(byte[] raw, byte[] clear)
  3. encrypt(byte[] raw, byte[] clear)
  4. encrypt(byte[] raw, byte[] clear)
  5. encrypt(byte[] source)
  6. encryptBase64(byte[] source)
  7. encryptBytes(String seed, byte[] cleartext)
  8. encryptBytes(byte[] data, byte[] key)
  9. encryptHex(String content, String key)