资讯专栏INFORMATION COLUMN

AES加密解密技术

villainhr / 3027人阅读

摘要:一般都听说过加密技术,加密确实强大。补充刚学习的时候,看到网上有人把密钥字节码转变成字符串保存,然后用来加密解密的时候,很有可能出错。因为不同语言的原因,字符串转变成字节码就有可能不再是原来的字节码了。

一般都听说过MD5加密技术,MD5加密确实强大。但那是非对称加密技术,也就是说从密文变成明文不是那么容易。当我们需要一种对称性加密技术,MD5就不适用了。比如视频加密解密,此时就可以用ASE加密解密了。

AES有更安全、灵活、有效率等优点,使用范围也很广,所以今天就讲讲AES加密如何使用,这里以java开展。

密钥

就是把明文转换为密文,密文转换为明文的一把钥匙。接下来我们会用ASE加密技术生成一把密钥。

public void generateSecretKey() {
    KeyGenerator keyGenerator = null;
    FileOutputStream fos = null;
    try {
        keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);//size
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyBytes = secretKey.getEncoded();
        fos = new FileOutputStream("key");
        fos.write(keyBytes);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

keyGenerator.init(128); 这里是初始化密钥的长度。翻看底层代码,发现密钥支持的长度为:128, 192 or 256。我们这里是128位的长度,也就是16byte。

补充: 刚学习的时候,看到网上有人把密钥(字节码)转变成字符串保存,然后用来加密解密的时候,很有可能出错。因为不同语言的原因,字符串转变成字节码就有可能不再是原来的字节码了。

密钥生成后,在项目目录下可以找到一个key文件。

加密

将明文和密钥一起,作为参数传入。

/**
 * ASE 加密
 * @param str 明文
 * @param key 秘钥
 * @return
 */
public static String enStr(String str, byte[] key) {
    Cipher cipher = null;
    SecretKey generateKey = null;
    try {
        generateKey = new SecretKeySpec(key, "AES");
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, generateKey);
        byte[] resultBytes = cipher.doFinal(str.getBytes());
        return Hex.encodeHexString(resultBytes);
    } catch (Exception e) {
        logger.error("AES加密出错", e);
    }
    return null;
}
解密

解密就是加密的互逆过程,所以代码很类似。

 /**
 * 解密
 * @param key 秘钥
 * @param str 密文
 * @return
 */
public static String deStr(String str, byte[] key) {
    Cipher cipher = null;
    SecretKey generateKey = null;
    try {
        generateKey = new SecretKeySpec(key, "AES");
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, generateKey);
        byte[] result = Hex.decodeHex(str.toCharArray());
        return new String(cipher.doFinal(result));

    } catch(Exception e) {
        logger.error("ASE解密出错", e);
    }
    return null;
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/70058.html

相关文章

  • 【大量干货】史上最完整的Tengine HTTPS原理解析、实践与调试

    摘要:内容主要有四个方面趋势基础实践调试。一趋势这一章节主要介绍近几年和未来的趋势,包括两大浏览器和对的态度,以及淘宝天猫和阿里云的实践情况。完整性是指为了避免网络中传输的数据被非法篡改,使用算法来保证消息的完整性。 摘要: 本文邀请阿里云CDN HTTPS技术专家金九,分享Tengine的一些HTTPS实践经验。内容主要有四个方面:HTTPS趋势、HTTPS基础、HTTPS实践、HTTPS...

    snowell 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<