AES加密解密全流程演示__api基础使用

Ashe / 2024-09-13 / 原文

public static void main(String[] args) throws Exception {
        // 共同约定秘钥和加密算法
        String content = "你好,世界";
        // AES密钥长度通常为128、192或256位
        String key = "1234567812345678"; // 16字节*8
        String algorithm = "AES";
        
        System.out.println("\n-----------发送方-----------\n");

        Cipher cipher = Cipher.getInstance(algorithm);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
        // 加密模式
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptBytes = cipher.doFinal(content.getBytes());
        String encryptText = new String(Base64.getEncoder().encode(encryptBytes)); // 密文
        System.out.println(encryptText);

        System.out.println("\n-----------接收方-----------\n");

        Cipher recieverCipher = Cipher.getInstance(algorithm);
        SecretKeySpec receiverSk = new SecretKeySpec(key.getBytes(), algorithm);
        // 解密模式
        recieverCipher.init(Cipher.DECRYPT_MODE, receiverSk);
        // 先将加密后的字符串解码回字节数据
        byte[] decodedBytes = Base64.getDecoder().decode(encryptText);
        byte[] plainBytes = recieverCipher.doFinal(decodedBytes);
        String plainText = new String(plainBytes); // 原文
        System.out.println(plainText);
    }