Android AES Encrypt encryptHex(String content, String key)

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

Description

encrypt Hex

Declaration

public static String encryptHex(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;

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

    public static String encryptHex(String content, String key) {
        try {/*from   w  ww .jav a 2  s .c  o  m*/
            byte[] res = encrypt(content.getBytes(UTF_8), key);
            return hexEncode(res);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encryptHex(String content, String username,
            String password) {
        return encryptHex(content, password + username);
    }

    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;
    }

    public static String hexEncode(byte[] data) {
        StringBuffer r = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            byte v = data[i];
            r.append(HEXCHARS[(v >> 4) & 0xf]).append(HEXCHARS[v & 0xf]);
        }
        return r.toString();
    }

    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[] source)
  2. encryptBase64(String content, String key)
  3. encryptBase64(byte[] source)
  4. encryptBytes(String seed, byte[] cleartext)
  5. encryptBytes(byte[] data, byte[] key)
  6. encryptHex(String content, String username, String password)
  7. encryptNumberWithAES(String number)
  8. encryptToBase64Text(String key, String src)
  9. encryptToBytes(String key, String src)