gpt4 book ai didi

java - Java 中 AES 加密的用户输入种子

转载 作者:行者123 更新时间:2023-12-01 05:05:18 26 4
gpt4 key购买 nike

所以我一直在编写这个程序来加密文件然后解密它,并且我希望伪随 secret 钥生成器将用户输入作为种子,以便可以从中创建 key 。请注意,我希望 key 依赖于字符串(即:如果我多次输入种子“hello”,它将每次使用相同的 key 加密文件),因为最终我会将加密和解密函数拆分为两个文件。

这是我的第一次尝试,基于 SecureRandom。还有更多代码,但只有 main 相关:

protected static final String ALGORITHM = "AES";

public static void main(String args[]) {

String stringKey = args[1];
byte[] seedArray = stringKey.getBytes();
SecureRandom sRandom = new SecureRandom(seedArray);
byte[] keyArray = new byte[16];
SecretKey sKey = new SecretKeySpec(keyArray, ALGORITHM);

try
{

Encrypter2 encrypter = new Encrypter2(sKey);

FileInputStream efis = new FileInputStream(args[0]);
FileOutputStream efos = new FileOutputStream("Encrypted");
encrypter.encrypt(efis, efos);

FileInputStream dfis = new FileInputStream("Encrypted");
FileOutputStream dfos = new FileOutputStream("Decrypted.txt");
encrypter.decrypt(dfis, dfos);

} catch (FileNotFoundException e1) {
System.out.println("File not found.");
e1.printStackTrace();
} catch (Exception e) {
System.out.println(e);
}
}

现在,这将为 Java 1.7 中的字符串输入创建一个唯一的键,但在 Java 1.6 中它会随机化。是否有另一种方法来生成取决于用户输入的字符串的用户种子 key ?提前致谢!

最佳答案

对于 AES 加密,您真正想要的是用作 key 的 16(或 32)字节数据。在这里,您将获取用户提供的字节,将它们用作随机字节生成器的种子,然后生成一些随机字节。

相反,您可以直接从用户提供的字符串生成字节,而无需使用 SecureRandom。使用“单向”哈希算法(如 SHA,代表安全哈希算法),您可以将用户提供的字符串转换为您需要的字节数。如果用户提供的字符串相同,则生成的字节将始终相同,无论 JVM 如何。

关于java - Java 中 AES 加密的用户输入种子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12792263/

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