You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中实现类似Go的AES/CFB/NoPadding加密及Base64编码

Java实现AES/CFB/NoPadding加密(对应Go代码逻辑)

首先,先拆解你提供的Go加密代码的核心逻辑:

  • 使用AES-128/256(取决于密钥长度,Go的aes.NewCipher支持16/24/32字节密钥,对应AES-128/192/256)
  • 采用CFB-128模式(Go的cipher.NewCFBEncrypter默认使用128位段大小,和块大小一致)
  • 无填充(NoPadding)
  • 生成16字节的随机IV(AES块大小),并将IV与密文拼接后做Base64编码返回

下面是完全匹配该逻辑的Java加密实现:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

public class AESEncryptor {

    public static String encrypt(byte[] key, byte[] data) throws Exception {
        // 验证密钥长度:AES支持16/24/32字节,对应128/192/256位
        if (key.length != 16 && key.length != 24 && key.length != 32) {
            throw new IllegalArgumentException("Invalid AES key length: must be 16, 24, or 32 bytes");
        }

        // 生成16字节随机IV(和Go代码一致,AES块大小)
        byte[] iv = new byte[16];
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(iv);

        // 初始化AES密钥和IV参数
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        // 初始化Cipher:指定CFB128模式(和Go的CFBEncrypter匹配)、无填充
        Cipher cipher = Cipher.getInstance("AES/CFB128/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

        // 执行加密
        byte[] ciphertext = cipher.doFinal(data);

        // 拼接IV和密文(IV在前,密文在后,和Go逻辑一致)
        byte[] ivAndCiphertext = new byte[iv.length + ciphertext.length];
        System.arraycopy(iv, 0, ivAndCiphertext, 0, iv.length);
        System.arraycopy(ciphertext, 0, ivAndCiphertext, iv.length, ciphertext.length);

        // Base64编码返回,和Go的encoding/base64对应
        return Base64.getEncoder().encodeToString(ivAndCiphertext);
    }

    // 测试用例
    public static void main(String[] args) throws Exception {
        byte[] key = "1234567890123456".getBytes(); // 16字节密钥,AES-128
        byte[] data = "Hello World!".getBytes();
        String encrypted = encrypt(key, data);
        System.out.println("Encrypted: " + encrypted);
    }
}

关键细节说明:

  • CFB模式段大小:Java中如果只写AES/CFB/NoPadding,默认会使用CFB-8模式,这和Go的CFB-128不兼容,所以必须明确指定AES/CFB128/NoPadding才能和Go代码的结果匹配。
  • IV处理:和Go一样,IV是随机生成的,并且需要和密文一起传递给解密端——解密时需要先从Base64解码后的字节数组中提取前16字节作为IV,剩下的作为密文。
  • 密钥长度:确保密钥长度是16/24/32字节,对应AES的三种密钥长度,否则会抛出异常。
  • 异常处理:实际使用时可以根据需要细化异常捕获(比如拆分NoSuchAlgorithmException、NoSuchPaddingException等),示例中为了简洁直接抛出Exception。

内容的提问来源于stack exchange,提问作者tarmek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:55:51