package com.fuying.sn.utils; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class CXAESUtil { public final static String HEX = "0123456789ABCDEF"; private static final int keyLenght = 16; private static final String defaultV = "0"; /** * 加密 * * @param key 密钥 * @param src 加密文本 * @return * @throws Exception */ public static String encrypt(String key, String src) { // /src = Base64.encodeToString(src.getBytes(), Base64.DEFAULT); byte[] rawKey = toMakekey(key, keyLenght, defaultV).getBytes();// key.getBytes(); try { byte[] result = encrypt(rawKey, src.getBytes("utf-8")); // result = Base64.encode(result, Base64.DEFAULT); return toHex(result); } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 密钥key ,默认补的数字,补全16位数,以保证安全补全至少16位长度,android和ios对接通过 * * @param str * @param strLength * @param val * @return */ private static String toMakekey(String str, int strLength, String val) { int strLen = str.length(); if (strLen < strLength) { while (strLen < strLength) { StringBuffer buffer = new StringBuffer(); buffer.append(str).append(val); str = buffer.toString(); strLen = str.length(); } } return str; } /** * 真正的加密过程 * 1.通过密钥得到一个密钥专用的对象SecretKeySpec * 2.Cipher 加密算法,加密模式和填充方式三部分或指定加密算 (可以只用写算法然后用默认的其他方式)Cipher.getInstance("AES"); * * @param key * @param src * @return * @throws Exception */ private static byte[] encrypt(byte[] key, byte[] src) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()])); byte[] encrypted = cipher.doFinal(src); return encrypted; } /** * 二进制转字符,转成了16进制 * 0123456789abcdefg * * @param buf * @return */ public static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); } }