java 加密、解密工具类 (相同入参 加密输出结果不同)

/**
 * @Author yanjun.hou
 * @Date 2021/11/30 10:34
 */
public class JiaJieMiUtils {
    public static final String KEY="12345bcdefabcdef";
        public static void main(String[] args) throws Exception {
            // 原文:
            String message = "Hello, world!";
            System.out.println("Message: " + message);
            /**
             * 加密
             */
            byte[] encrypt = encrypt(KEY.getBytes("UTF-8"), message.getBytes("UTF-8"));
            System.out.println("密文:"+Base64.getEncoder().encodeToString(encrypt));
            /**
            *解密
            */
            byte[] decrypt = decrypt(KEY.getBytes(), encrypt);
            System.out.println("明文:"+new String(decrypt,"UTF-8"));
        }

    // 加密:
        public static byte[] encrypt(byte[] key, byte[] input) throws GeneralSecurityException {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            // CBC模式需要生成一个16 bytes的initialization vector:
            SecureRandom sr = SecureRandom.getInstanceStrong();
            byte[] iv = sr.generateSeed(16);
            IvParameterSpec ivps = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivps);
            byte[] data = cipher.doFinal(input);
            // IV不需要保密,把IV和密文一起返回:
            return join(iv, data);
        }

        // 解密:
        public static byte[] decrypt(byte[] key, byte[] input) throws GeneralSecurityException {
            // 把input分割成IV和密文:
            byte[] iv = new byte[16];
            byte[] data = new byte[input.length - 16];
            System.arraycopy(input, 0, iv, 0, 16);
            System.arraycopy(input, 16, data, 0, data.length);
            // 解密:
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            IvParameterSpec ivps = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivps);
            return cipher.doFinal(data);
        }

        public static byte[] join(byte[] bs1, byte[] bs2) {
            byte[] r = new byte[bs1.length + bs2.length];
            System.arraycopy(bs1, 0, r, 0, bs1.length);
            System.arraycopy(bs2, 0, r, bs1.length, bs2.length);
            return r;
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

还算善良_

如果对你的工作有所帮助,拜托啦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值