AES加、解密

Android端

public class EncryptUtil {
    static Boolean b = true;

    // 注意: 这里的password(秘钥必须是16位的)
    public static final String keyBytes = "3epj7jhny345mwe2";
    //    public static final String keyBytes = "test7jhny345mwe2";

    static final String algorithmStr = "AES/ECB/PKCS5Padding";

    private static final Object TAG = "AES";

    static private KeyGenerator keyGen;

    static private Cipher cipher;

    static boolean isInited = false;

    private static void init() {
        try {
            /**
             * 为指定算法生成一个 KeyGenerator 对象。 此类提供(对称)密钥生成器的功能。 密钥生成器是使用此类的某个
             * getInstance 类方法构造的。 KeyGenerator 对象可重复使用,也就是说,在生成密钥后, 可以重复使用同一
             * KeyGenerator 对象来生成进一步的密钥。 生成密钥的方式有两种:与算法无关的方式,以及特定于算法的方式。
             * 两者之间的惟一不同是对象的初始化: 与算法无关的初始化 所有密钥生成器都具有密钥长度 和随机源 的概念。 此
             * KeyGenerator 类中有一个 init 方法,它可采用这两个通用概念的参数。 还有一个只带 keysize 参数的
             * init 方法, 它使用具有最高优先级的提供程序的 SecureRandom 实现作为随机源 (如果安装的提供程序都不提供
             * SecureRandom 实现,则使用系统提供的随机源)。 此 KeyGenerator 类还提供一个只带随机源参数的 inti
             * 方法。 因为调用上述与算法无关的 init 方法时未指定其他参数,
             * 所以由提供程序决定如何处理将与每个密钥相关的特定于算法的参数(如果有)。 特定于算法的初始化
             * 在已经存在特定于算法的参数集的情况下, 有两个具有 AlgorithmParameterSpec 参数的 init 方法。
             * 其中一个方法还有一个 SecureRandom 参数, 而另一个方法将已安装的高优先级提供程序的 SecureRandom
             * 实现用作随机源 (或者作为系统提供的随机源,如果安装的提供程序都不提供 SecureRandom 实现)。
             * 如果客户端没有显式地初始化 KeyGenerator(通过调用 init 方法), 每个提供程序必须提供(和记录)默认初始化。
             */
            keyGen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 初始化此密钥生成器,使其具有确定的密钥长度。
        keyGen.init(128); // 128位的AES加密
        try {
            // 生成一个实现指定转换的 Cipher 对象。
            cipher = Cipher.getInstance(algorithmStr);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        // 标识已经初始化过了的字段
        isInited = true;
    }

    private static byte[] genKey() {
        if (!isInited) {
            init();
        }
        // 首先 生成一个密钥(SecretKey),
        // 然后,通过这个秘钥,返回基本编码格式的密钥,如果此密钥不支持编码,则返回 null。
        return keyGen.generateKey().getEncoded();
    }

    private static byte[] encrypt(byte[] content, byte[] keyBytes) {
        byte[] encryptedText = null;
        if (!isInited) {
            init();
        }
        /**
         * 类 SecretKeySpec 可以使用此类来根据一个字节数组构造一个 SecretKey, 而无须通过一个(基于 provider
         * 的)SecretKeyFactory。 此类仅对能表示为一个字节数组并且没有任何与之相关联的钥参数的原始密钥有用
         * 构造方法根据给定的字节数组构造一个密钥。 此构造方法不检查给定的字节数组是否指定了一个算法的密钥。
         */
        Key key = new SecretKeySpec(keyBytes, "AES");
        try {
            // 用密钥初始化此 cipher。
            cipher.init(Cipher.ENCRYPT_MODE, key);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        try {
            // 按单部分操作加密或解密数据,或者结束一个多部分操作。(不知道神马意思)
            encryptedText = cipher.doFinal(content);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return encryptedText;
    }

    private static byte[] encrypt(String content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);// algorithmStr
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// ?
            byte[] result = cipher.doFinal(byteContent);
            return result; //
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] decrypt(byte[] content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);// algorithmStr
            cipher.init(Cipher.DECRYPT_MODE, key);// ?
            byte[] result = cipher.doFinal(content);
            return result; //
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] getKey(String password) {
        byte[] rByte = null;
        if (password != null) {
            rByte = password.getBytes();
        } else {
            rByte = new byte[24];
        }
        return rByte;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 加密
     */
    public static String encode(String content) {
        // 加密之后的字节数组,转成16进制的字符串形式输出
        if (!b) {
            return content;
        }
        return parseByte2HexStr(encrypt(content, keyBytes));
    /*    String str=parseByte2HexStr(encrypt(content, keyBytes));
        try {
            return MD5.MD5_16bit(str)+parseByte2HexStr(encrypt(content, keyBytes));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }*/
        //  return null;
    }

    /**
     * 解密
     */
    public static String decode(String content) {
        if (!b) {
            return content;
        }
        // 解密之前,先将输入的字符串按照16进制转成二进制的字节数组,作为待解密的内容输入
        byte[] b = decrypt(parseHexStr2Byte(content), keyBytes);
        return new String(b);
    }

    // 测试用例
    public static void test1() {
        String content = "hello abcdefggsdfasdfasdf";
        String pStr = encode(content);
        System.out.println("加密前:" + content);
        System.out.println("加密后:" + pStr);

        String postStr = decode(pStr);
        System.out.println("解密后:" + postStr);
    }

    public static void main(String[] args) {
        test1();
    }
}

JAVA端

public class A {

    // private static final Log log = LogFactory.getLog(HttpClientUtil.class);
    // private static final Propertie pe=new Propertie();
    /*private static String aeskey=pe.getAeskey();
    private static String edswitch=pe.getEdswitch();*/
    
    static final String algorithmStr = "AES/ECB/PKCS5Padding";

    private static final Object TAG = "AES";

    static private KeyGenerator keyGen;

    static private Cipher cipher;

    static boolean isInited = false;
    
    // 注意: 这里的password(秘钥必须是16位的)
    private static final String keyBytes = "1234567890abcdef";

    private static void init() {
        try {
            /**
             * 为指定算法生成一个 KeyGenerator 对象。 此类提供(对称)密钥生成器的功能。 密钥生成器是使用此类的某个
             * getInstance 类方法构造的。 KeyGenerator 对象可重复使用,也就是说,在生成密钥后, 可以重复使用同一
             * KeyGenerator 对象来生成进一步的密钥。 生成密钥的方式有两种:与算法无关的方式,以及特定于算法的方式。
             * 两者之间的惟一不同是对象的初始化: 与算法无关的初始化 所有密钥生成器都具有密钥长度 和随机源 的概念。 此
             * KeyGenerator 类中有一个 init 方法,它可采用这两个通用概念的参数。 还有一个只带 keysize 参数的
             * init 方法, 它使用具有最高优先级的提供程序的 SecureRandom 实现作为随机源 (如果安装的提供程序都不提供
             * SecureRandom 实现,则使用系统提供的随机源)。 此 KeyGenerator 类还提供一个只带随机源参数的 inti
             * 方法。 因为调用上述与算法无关的 init 方法时未指定其他参数,
             * 所以由提供程序决定如何处理将与每个密钥相关的特定于算法的参数(如果有)。 特定于算法的初始化
             * 在已经存在特定于算法的参数集的情况下, 有两个具有 AlgorithmParameterSpec 参数的 init 方法。
             * 其中一个方法还有一个 SecureRandom 参数, 而另一个方法将已安装的高优先级提供程序的 SecureRandom
             * 实现用作随机源 (或者作为系统提供的随机源,如果安装的提供程序都不提供 SecureRandom 实现)。
             * 如果客户端没有显式地初始化 KeyGenerator(通过调用 init 方法), 每个提供程序必须提供(和记录)默认初始化。
             */
            keyGen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 初始化此密钥生成器,使其具有确定的密钥长度。
        keyGen.init(128); // 128位的AES加密
        try {
            // 生成一个实现指定转换的 Cipher 对象。
            cipher = Cipher.getInstance(algorithmStr);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        // 标识已经初始化过了的字段
        isInited = true;
    }

    private static byte[] genKey() {
        if (!isInited) {
            init();
        }
        // 首先 生成一个密钥(SecretKey),
        // 然后,通过这个秘钥,返回基本编码格式的密钥,如果此密钥不支持编码,则返回 null。
        return keyGen.generateKey().getEncoded();
    }

    private static byte[] encrypt(byte[] content, byte[] keyBytes) {
        byte[] encryptedText = null;
        if (!isInited) {
            init();
        }
        /**
         * 类 SecretKeySpec 可以使用此类来根据一个字节数组构造一个 SecretKey, 而无须通过一个(基于 provider
         * 的)SecretKeyFactory。 此类仅对能表示为一个字节数组并且没有任何与之相关联的钥参数的原始密钥有用
         * 构造方法根据给定的字节数组构造一个密钥。 此构造方法不检查给定的字节数组是否指定了一个算法的密钥。
         */
        Key key = new SecretKeySpec(keyBytes, "AES");
        try {
            // 用密钥初始化此 cipher。
            cipher.init(Cipher.ENCRYPT_MODE, key);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        try {
            // 按单部分操作加密或解密数据,或者结束一个多部分操作。(不知道神马意思)
            encryptedText = cipher.doFinal(content);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return encryptedText;
    }

    private static byte[] encrypt(String content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);// algorithmStr
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// ?
            byte[] result = cipher.doFinal(byteContent);
            return result; //
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] decrypt(byte[] content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);// algorithmStr
            cipher.init(Cipher.DECRYPT_MODE, key);// ?
            byte[] result = cipher.doFinal(content);
            return result; //
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] getKey(String password) {
        byte[] rByte = null;
        if (password != null) {
            rByte = password.getBytes();
        } else {
            rByte = new byte[24];
        }
        return rByte;
    }

    /**
     * 将二进制转换成16进制
     * 
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     * 
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    

    /**
     * 加密
     */
    public static String encode(String content) {
        // 加密之后的字节数组,转成16进制的字符串形式输出
        return parseByte2HexStr(encrypt(content, keyBytes));
    }

    /**
     * 解密
     */
    public static String decode(String content) {
        // 解密之前,先将输入的字符串按照16进制转成二进制的字节数组,作为待解密的内容输入
        byte[] b = decrypt(parseHexStr2Byte(content), keyBytes);
        return new String(b);
    }

    // 测试用例
    public static void test1() {
        String content = "hengks和人们";
    
        String pStr = encode(content);
        System.out.println("加密前:" + content);
        System.out.println("加密后:" + pStr);

        String postStr = decode(pStr);
        System.out.println("解密后:" + postStr);
    }

    public static void main(String[] args) {
        test1();
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容