AES 加密 绝对好用

自己测过兼容6.0到9.0的AES 工具类采用AES/CBC/PKCS5Padding 绝对好用的哦

 

 

调用方式

        String enText = AesUtils2.encrypt(AesUtils2.KEY, para);
//            String enText = AESUtil2.encrypt(para,AES_KEY);
        Toast.makeText(context, " 参数:" + para + "加密后:" + enText, Toast.LENGTH_SHORT).show();
        Log.i(TAG, "参数:" + para + "加密后:" + enText);
//        String deText = AesUtils.decrypt(AES_KEY, enText);
        String deText = AesUtils2.decrypt(AesUtils2.KEY, enText);
        Log.i(TAG, "解密后:" + deText);

工具类

public class AesUtils2 {
    private final static String HEX = "0123456789ABCDEF";

    /***
     * AES 公钥 必须16位
     */
    public final static String KEY = "0123456789654321";
    private static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";//AES是加密方式 CBC是工作模式 PKCS5Padding是填充模式
    //    private static final String ECB_PKCS5_PADDING = "AES/ECB/PKCS5Padding";//AES是加密方式 CBC是工作模式 PKCS5Padding是填充模式
    private static final String AES = "AES";//AES 加密
    private static final String SHA1PRNG = "SHA1PRNG";// SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法
    private static String ivParameter = "qwertyuiopasdfgh";//16位的偏移量

    /**
     * 生成随机数,可以当做动态的密钥 加密和解密的密钥必须一致,不然将不能解密
     */
    public static String generateKey() {
        try {
            SecureRandom localSecureRandom = SecureRandom.getInstance(SHA1PRNG);
            byte[] bytes_key = new byte[20];
            localSecureRandom.nextBytes(bytes_key);
            String str_key = toHex(bytes_key);
            return str_key;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 对密钥进行处理
    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(AES);
        //for android
        SecureRandom sr = null;
        // 在4.2以上版本中,SecureRandom获取方式发生了改变
        int sdk_version = android.os.Build.VERSION.SDK_INT;
        if (sdk_version > 23) {  // Android  6.0 以上
            sr = SecureRandom.getInstance(SHA1PRNG, new CryptoProvider());
        } else if (android.os.Build.VERSION.SDK_INT >= 17) {   //4.2及以上
            sr = SecureRandom.getInstance(SHA1PRNG, "Crypto");
        } else {
            sr = SecureRandom.getInstance(SHA1PRNG);
        }


        // for Java
        // secureRandom = SecureRandom.getInstance(SHA1PRNG);
        sr.setSeed(seed);
        kgen.init(128, sr); //256 bits or 128 bits,192bits
        //AES中128位密钥版本有10个加密循环,192比特密钥版本有12个加密循环,256比特密钥版本则有14个加密循环。
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }

    /*
     * 加密
     */
    public static String encrypt(String key, String cleartext) {
        if (TextUtils.isEmpty(cleartext)) {
            return cleartext;
        }
        try {
            byte[] result = encrypt(key, cleartext.getBytes());
//            return Base64Encoder.encode(result);
            return new String(Base64.encode(result, Base64.DEFAULT));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密 CBC
     */
    private static byte[] encrypt(String key, byte[] data) throws Exception {

        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
//        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(AES);
//        Key aeskey = keyfactory.generateSecret(skeySpec);
        Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());//使用CBC模式,需要一个向量iv
//        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(data);
        return encrypted;
    }
//    /**
//     * 加密 EBC
//     */
//    private static byte[] encrypt(String key, byte[] clear) throws Exception {
//        byte[] raw = getRawKey(key.getBytes());
//        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
//        Cipher cipher = Cipher.getInstance(ECB_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
//        cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
//        byte[] encrypted = cipher.doFinal(clear);
//        return encrypted;
//    }

    /**
     * 解密
     */
    public static String decrypt(String key, String encrypted) {
        if (TextUtils.isEmpty(encrypted)) {
            return encrypted;
        }
        try {
//            byte[] enc = Base64Decoder.decodeToBytes(encrypted);
            byte[] enc = Base64.decode(encrypted, Base64.DEFAULT);
            byte[] result = decrypt(key, enc);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密 CBC
     */
    private static byte[] decrypt(String key, byte[] encrypted) throws Exception {
//        byte[] raw = getRawKey(key.getBytes());
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), AES);
        Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());//使用CBC模式,需要一个向量iv
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
//        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }
//    /**
//     * 解密 EBC
//     */
//    private static byte[] decrypt(String key, byte[] encrypted) throws Exception {
//        byte[] raw = getRawKey(key.getBytes());
//        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
//        Cipher cipher = Cipher.getInstance(ECB_PKCS5_PADDING);
//        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
//        byte[] decrypted = cipher.doFinal(encrypted);
//        return decrypted;
//    }

    //二进制转字符
    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));
    }


    // 增加  CryptoProvider  类

    public static class CryptoProvider extends Provider {
        /**
         * Creates a Provider and puts parameters
         */
        public CryptoProvider() {
            super("Crypto", 1.0, "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)");
            put("SecureRandom.SHA1PRNG",
                    "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl");
            put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
        }
    }
}

 

你可能感兴趣的:(AES 加密 绝对好用)