美文网首页
Android AES 加密

Android AES 加密

作者: 钢镚koala | 来源:发表于2018-11-22 11:07 被阅读0次

关于加密的几种方式:https://www.jianshu.com/p/18a577ae6b50
最近在做项目的时候,发现7.0以上系统,原来的AES中部分类已经被废弃。所以,如果还是采用原来的加密方法可能会通不过。这里,我在网上搜到一个比较好使的,封装成工具类,大家可以试试。本人测试是通过的。

import android.text.TextUtils;
import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * describe: AES加密算法
 */

public class AesUtils {

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

    private static byte[] encrypt(String password, String clear) throws Exception {
        // 创建AES秘钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(password.getBytes(), "AES/CBC/PKCS5PADDING");
        // 创建密码器
        Cipher cipher = Cipher.getInstance("AES");
        // 初始化加密器
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        // 加密
        return cipher.doFinal(clear.getBytes("UTF-8"));
    }

    private byte[] decrypt(byte[] content, String password) throws Exception {
        // 创建AES秘钥
        SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES/CBC/PKCS5PADDING");
        // 创建密码器
        Cipher cipher = Cipher.getInstance("AES");
        // 初始化解密器
        cipher.init(Cipher.DECRYPT_MODE, key);
        // 解密
        return cipher.doFinal(content);
    }

}

相关文章

网友评论

      本文标题:Android AES 加密

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