gpt4 book ai didi

Java AES/GCM/NoPadding 加密因特殊字符而失败

转载 作者:行者123 更新时间:2023-11-29 08:20:53 32 4
gpt4 key购买 nike

我遵循了几个示例,并在尝试实现此处引用的 AES/GCM/NoPadding 时:https://www.strongauth.com/samplecode/GCM.java我无法加密任何包含特殊字符(即 ø)的文本。

最终它在 doFinal 内部失败了javax.crypto.ShortBufferException:输出缓冲区必须(至少)30 字节长但似乎我一定做错了什么。我错过了什么?

简单 POC:

public class Example {

private static final String CIPHER_TRANSFORM = "AES/GCM/NoPadding";

public static void main(String[] args) {

String key = generateKey("AES", 256, "seed");
encryptText("text containing a ø character", key, "TOKENTOKENTOKENTOKEN", "AES");
}

private static String generateKey(String alg, int size, String seed) {

try {
SecureRandom securerandom = SecureRandom.getInstance("SHA1PRNG");
securerandom.setSeed(seed.getBytes("UTF-8"));
KeyGenerator kg = KeyGenerator.getInstance(alg);
kg.init(size, securerandom);
SecretKey sk = kg.generateKey();
return new String(Base64.getEncoder().encode(sk.getEncoded()), "UTF-8");
}
catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
System.err.println(ex);
}
return null;
}

private static String encryptText(String PLAINTEXT, String PLAINTEXTKEY, String TOKEN, String alg) {

try {
// Create SecretKey & Cipher
SecretKeySpec sks = new SecretKeySpec(Base64.getDecoder().decode(PLAINTEXTKEY), alg);
Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORM);

// Setup byte arrays
byte[] input = PLAINTEXT.getBytes("UTF-8");
byte[] tkb = TOKEN.getBytes("UTF-8");
byte[] iv = new byte[12];
System.arraycopy(tkb, 4, iv, 0, 12);
cipher.init(Cipher.ENCRYPT_MODE, sks, new GCMParameterSpec(128, iv));
cipher.updateAAD(tkb);
byte[] opbytes = new byte[cipher.getOutputSize(PLAINTEXT.length())];

// Perform crypto
int ctlen = cipher.update(input, 0, input.length, opbytes);
ctlen += cipher.doFinal(opbytes, ctlen);
byte[] output = new byte[ctlen];
System.arraycopy(opbytes, 0, output, 0, ctlen);
return new String(Base64.getEncoder().encode(output), "UTF-8");

}
catch (InvalidAlgorithmParameterException | UnsupportedEncodingException |
IllegalBlockSizeException | BadPaddingException | InvalidKeyException |
NoSuchAlgorithmException | NoSuchPaddingException | ShortBufferException ex) {
System.err.println(ex);
}
return null;
}
}

最佳答案

你的问题是这一行:

byte[] opbytes = new byte[cipher.getOutputSize(PLAINTEXT.length())];

UTF-8 rune 中字符串的长度并不总是与底层字节数组的长度相同。您应该在此处使用 input 的长度,而不是 PLAINTEXT

关于Java AES/GCM/NoPadding 加密因特殊字符而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652436/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com