gpt4 book ai didi

java - GNU Crypto Encrypt 返回空白字符串

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:26 24 4
gpt4 key购买 nike

我正在使用 GNU Crypto 库来加密简单的字符串。我相信我已经正确遵循了文档,但问题是它只返回一个由空格组成的空白字符串(在本例中为 5 个字符)。我不确定是否我错过了编码或者是否存在一些编码问题。我希望这不是一件令人尴尬的简单事情。

import gnu.crypto.cipher.CipherFactory;
import gnu.crypto.cipher.IBlockCipher;
import java.util.HashMap;
import java.util.Map;

public class FTNSAMain {

public static void main(String[] args) throws Exception {
String data = "Apple";
String key = "ABCDEFGHIJKLMNOP";

byte[] temp = Encrypt(data.getBytes(), key.getBytes(), "AES");
System.out.println(new String(temp));
}

public static byte[] Encrypt(byte[] input, byte[] key, String algorithm) throws Exception {
byte[] output = new byte[input.length];

IBlockCipher cipher = CipherFactory.getInstance(algorithm);
Map attributes = new HashMap();

attributes.put(IBlockCipher.CIPHER_BLOCK_SIZE, 16);
attributes.put(IBlockCipher.KEY_MATERIAL, key);
cipher.init(attributes);

int bs = cipher.currentBlockSize();
for (int i = 0; i + bs < input.length; i += bs) {
cipher.encryptBlock(input, i, output, i);
}
return output;
}

}

最佳答案

GNU Crypto 文档对 void encryptBlock(..) 方法有以下说明:

Encrypts a block of bytes from plaintext starting at inOffset, storing the encrypted bytes in ciphertext, starting at outOffset. It is up to the programmer to ensure that there is at least one full block in plaintext from inOffset and space for one full block in ciphertext from outOffset. A java.lang.IllegalStateException will be thrown if the cipher has not been initialized.

您的输入:

String data = "Apple";

不是完整的数据 block ,因为 AES 需要16 字节 block 中的数据。另外,您的输出缓冲区也太短。

对于初学者,请尝试使用最终为 16 字节的输入进行加密,例如:

String data = "Apple56789abcdef";

关于java - GNU Crypto Encrypt 返回空白字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32040131/

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