美文网首页
记:Android中AES加密工具类

记:Android中AES加密工具类

作者: 爱吃板栗的小女孩 | 来源:发表于2019-07-16 10:06 被阅读0次

此处密码模式为:AES/ECB/PKCS5Padding

public class AESUtil {
    static final String algorithmStr = "AES/ECB/PKCS5Padding";

    private static final Object TAG = "AES";

    private static final String PWD = "aaa";//(此处密码不是随机生成,是后台生成规定好)


    public static String encryptToBase64(String data){
        try {
            if (!TextUtils.isEmpty(data)) {
                byte[] valueByte = encrypt(data.getBytes("UTF-8"), PWD.getBytes("UTF-8"));
                return encodeBase64(valueByte);
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] encrypt(byte[] data, byte[] key) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);
            cipher.init(Cipher.ENCRYPT_MODE, seckey);
            byte[] result = cipher.doFinal(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private static String encodeBase64(byte[] input) {
        try {
            return new String(Base64.encodeToString(input,Base64.NO_WRAP));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}

相关文章

网友评论

      本文标题:记:Android中AES加密工具类

      本文链接:https://www.haomeiwen.com/subject/rvczkctx.html