当前位置: 首页 > 知识库问答 >
问题:

AES-256-GCM译码器

阴高寒
2023-03-14

我试着用java7实现AES-256-GCM解码,我在GCM中遇到了mac检查失败的响应,请帮帮我,谢谢大家。

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

  public static void main(String[] args) throws Exception {
    String iv = "35d117c42d1c1835420b6b9942dd4f1b"; // utf-8
    String key = "3a7bd3e2360a3d29eea436fcfb7e44c7"; // utf-8
    String hexCipherString = "07a604fc0c143a6e"; // hex
    String hexAuthTagString = "984e81176ff260717beb184db3d73753"; //hex

    byte[] decodedCipherHexBtye = Hex.decodeHex(hexCipherString.toCharArray());
    byte[] base64Cipher = Base64.decodeBase64(decodedCipherHexBtye);
    byte[] decodedAuthTagHex = Hex.decodeHex(hexAuthTagString.toCharArray());
    byte[] base64AuthTag = Base64.decodeBase64(decodedAuthTagHex);

    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
    byte[] gcmIv = iv.getBytes("UTF-8");

    Security.addProvider(new BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
    GCMParameterSpec params = new GCMParameterSpec(base64AuthTag.length * Byte.SIZE, gcmIv);
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, params);
    cipher.updateAAD(base64AuthTag);
    byte[] result = cipher.doFinal(base64Cipher);
    System.out.println(Base64.encodeBase64(result));
  }

我很期待Base64Encode的预期结果:DGVZDA==

共有1个答案

姬裕
2023-03-14

如何处理安全警告注释以实现安全代码。

警告中的核心问题是每次加密都需要随机生成的IV(一组真正随机的字节)

当您制作密码时,这里是一个使用Java8Oracle SE的具体示例

       val cipher = Cipher.getInstance("some scheme", "some provider");

至少在Oracle Java8中,这很容易,

用上面的密码

    cipher.getIV()

密码对象的实例方法是安全的(请参阅

    ivParams = IvParameterSpec( cipher.getIV())
    cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
 类似资料: