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;
        }
    }


版权声明:本文为weixin_46522411原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。