AES加解密工具封装

在日常开发工作中,涉及加解密的应用场景有很多,以下为常见的加解密应用场景:

  1. 用户密码存储

    用户密码在存储时通常不应该以明文形式保存,而应该经过加密处理。这通常涉及到用户注册时的密码加密,以及用户登录验证时的密码解密比对。

  2. 敏感数据存储

    数据库中的敏感信息(如个人身份证号、银行账号、信用卡号等)需要加密存储,以防止数据库泄露时泄漏敏感信息。

  3. 数据传输安全

    在网络传输过程中,特别是通过公共网络(如互联网)传输敏感信息时,需要使用加密来保证数据在传输过程中不被窃取或篡改。

  4. 文件加密

    对于本地存储的敏感文件或数据文件,可以使用加密技术保证文件在存储和传输时的安全性。

  5. 数字签名

    在加密通信中,数字签名用于验证消息的完整性和真实性,确保消息在传输过程中没有被篡改或伪造。

  6. 会话加密

    在Web开发中,通过 HTTPS 协议对会话进行加密,以防止会话劫持和信息泄露。

  7. 数据库字段加密

    对数据库中特定字段(如手机号码、地址等)进行加密处理,以增强数据安全性。

  8. 密码重置链接

    生成和验证密码重置链接时,链接中的敏感信息应该使用加密算法加以保护,避免链接被篡改或恶意利用。

话不多说,上代码。。。。。
引入依赖

		<dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
            <version>1.46</version>
        </dependency>

工具类封装

public class AESUtil {


    private static final Pattern PATTERN = Pattern.compile("\r|\n");
    // 编码
    private static final String CHARSET_NAME = "UTF-8";
    // 算法名称
    private static final String AES_NAME = "AES";
    // 密钥KEY(根据实际情况自己定义密钥)
    private static final String KEY = "sadfsdafdsfdsf";
    // 偏移量(根据实际情况自己定义)
    private static final String IV = "sdfsdfdsf";
    // 加解密算法/模式/填充方式
    private static final String ALGORITHM = "AES/CBC/PKCS7Padding";

    /**
     * 加密方法
     * @param content 要加密的字符串
     * @return
     */
    public static String encrypt(String content) {
        byte[] encryptedText = null;
        try {
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            // 转化成JAVA的密钥格式
            Key key = new SecretKeySpec(KEY.getBytes(CHARSET_NAME), AES_NAME);
            // 初始化cipher
            Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes(CHARSET_NAME)));
            encryptedText = cipher.doFinal(content.getBytes(CHARSET_NAME));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String result=new BASE64Encoder().encode(encryptedText);
        //去换行符
        Matcher matcher = PATTERN.matcher(result);
        result = matcher.replaceAll("");
        return result;
    }

    /**
     * 解密
     *
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        try {
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            Key key = new SecretKeySpec(KEY.getBytes(CHARSET_NAME), AES_NAME);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
            String result=new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(content)),CHARSET_NAME);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //口令解密
    public static String decryptPassword(String result){
        String[] resultArr=result.split("\"authPasswd\":\"");
        for(String str:resultArr){
            if(str.contains("\\r\\n")){
                String passwod=str.split("==")[0]+"==";
                String decode=AESUtil.decrypt(passwod);
                result=result.replace(passwod+"\\r\\n",decode);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        //String aa=encrypt("337788");
        System.out.println(encrypt("dfdfdddd"));
    }
}

解读
1、KEY 和 IV 是用于 AES 加密和解密的密钥和偏移量。在实际使用中,应该使用更复杂和安全的方式来管理和生成这些值。
2、ALGORITHM 指定了 AES 算法使用 CBC 模式和 PKCS7 填充方式进行加解密。CBC (Cipher Block Chaining) 模式需要一个初始化向量 (IV)。
3、encrypt 方法使用 Bouncy Castle 提供的实现来加密 content 字符串。它首先将 KEY 转换为 SecretKeySpec 对象,然后初始化 Cipher 对象以进行加密操作。加密后的结果通过 Base64 编码转换成字符串,并移除其中的换行符。
4、decrypt 方法用于解密经过 AES 加密后的字符串 content。它也首先添加了 Bouncy Castle 提供的安全提供者,然后初始化 Cipher 对象进行解密操作。解密过程中使用了相同的 KEY 和 IV,并且通过 Base64 解码将加密文本转换为原始字符串。
5、decryptPassword 方法用于解密特定格式的密码字段。它首先根据 “authPasswd”:" 进行拆分,然后查找包含 \r\n 的部分,这通常用于处理特定的文本格式。然后它对找到的密码部分进行解密并替换原始文本中的加密字符串。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中使用AES加密解密可以通过使用Javajavax.crypto包中的相关类来实现。下面是一个简单的示例代码: 首先,你需要确保你的项目中已经引入了Java Cryptography Extension(JCE)库,该库提供了AES算法的实现。 ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESUtil { private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String AES_SECRET_KEY = "your-secret-key"; // 替换成你自己的密钥 private static final String AES_IV = "your-iv"; // 替换成你自己的IV public static String encrypt(String data) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(AES_SECRET_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); IvParameterSpec ivParameterSpec = new IvParameterSpec(AES_IV.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] encryptedBytes = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } public static String decrypt(String encryptedData) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(AES_SECRET_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); IvParameterSpec ivParameterSpec = new IvParameterSpec(AES_IV.getBytes()); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return new String(decryptedBytes); } } ``` 使用该工具类,你可以进行AES加密和解密操作。你需要替换`AES_SECRET_KEY`和`AES_IV`为你自己的密钥和初始化向量(IV)。 示例用法: ```java public class Main { public static void main(String[] args) throws Exception { String data = "Hello, World!"; String encryptedData = AESUtil.encrypt(data); System.out.println("Encrypted: " + encryptedData); String decryptedData = AESUtil.decrypt(encryptedData); System.out.println("Decrypted: " + decryptedData); } } ``` 这是一个基本的示例,你可以根据自己的需求进行进一步的封装和调整。记得在实际使用中要采取适当的安全措施,并根据需要选择合适的AES加密模式和填充方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值