【问题标题】:User-input seed for AES encryption in JavaJava 中用于 AES 加密的用户输入种子
【发布时间】:2012-10-09 03:00:22
【问题描述】:

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

这是我的第一次尝试,基于 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 中它是随机的。是否有另一种生成取决于用户输入的字符串的用户种子密钥的方法?提前致谢!

【问题讨论】:

    标签: java aes seed


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      • 2015-04-21
      • 2015-09-10
      • 2010-11-02
      • 2018-01-04
      • 1970-01-01
      • 2011-11-10
      相关资源
      最近更新 更多