Android AES加解密,与其他平台对接的问题解决方案

AES百度百科

AES中主要组成:明文(需要加密的数据)、秘钥(用于加解密)、偏移量(增加破解难度)

秘钥:如果不对秘钥做处理,秘钥长度一定要进行处理仅支持 128、192、256 比特三种;

偏移量:偏移量需要固定128比特;

加密模式:此文章仅对于AES/CBC/PKCS5Padding 进行说明;AES加密模式,CBC工作模式,PACS5Padding 填充模式。

加密方法为:

    public static String aesEncrypt(String str, String key, String iv) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64Decoder.decodeToBytes(key), "AES"), new IvParameterSpec(Base64Decoder.decodeToBytes(iv)));
        byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
        return Base64Encoder.encode(bytes);
    }
解密方法为:

    public static String aesDecrypt(String str, String key, String iv) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64Decoder.decodeToBytes(key), "AES"), new IvParameterSpec(Base64Decoder.decodeToBytes(iv)));
        byte[] bytes = Base64Decoder.decodeToBytes(str);
        bytes = cipher.doFinal(bytes);
        return new String(bytes, "utf-8");
    }
在加解密中需要注意的是:对于数据的处理编码方式要一致;上述方法中没有对传入数据进行验证合法性,也没有进行对数据进行处理有时间在进行完善;使用时主要保证  key 与iv 的长度 顶部有介绍;



你可能感兴趣的:(Android,加解密)