java - 使用 byte[] 生成 key 会为 MAC 和 Windows 生成不同的结果

标签 java windows macos encryption bouncycastle

我正在尝试使用 byte[] 生成 key ,即从字符串生成 key 。 我的类(class)是 final类,并且我的方法是静态的。

类(class):

public final class Operation {

    public static Key getKey(byte[] arr)
    {
        Key key = null;
    KeyGenerator keyGen;
        Security.addProvider(new BouncyCastleProvider());
    try
    {
            keyGen = KeyGenerator.getInstance("AES", "BC");
            if(arr == null)
                keyGen.init(192);
            else
                keyGen.init(new SecureRandom(arr));
            key = keyGen.generateKey();
    }
    catch (NoSuchAlgorithmException e)
    {
            System.err.println(e);  
    } catch (NoSuchProviderException e) {
            System.err.println(e);
        }

        return key;
    }

    public static String getKeyAsString(Key key)
    {
        return  new String(Base64.encode(key.getEncoded()));
    }

    public static Key getKeyFromString(String string)
    {
        return new SecretKeySpec(Base64.decode(string.getBytes()), "AES");
    }

}

主函数有以下几行:

    Key key1 = Operation.getKey("admin".getBytes());
    Key key2 = Operation.getKey("admin".getBytes());

    System.out.println(new String(Base64.encode(key1.getEncoded())));
    System.out.println(new String(Base64.encode(key2.getEncoded())));

我在 Windows 上得到相同的按键输出,例如:

4BjJkLCJ3LyPluKkd2DBgqghhNfSgzKD
4BjJkLCJ3LyPluKkd2DBgqghhNfSgzKD

但 Mac 操作系统并非如此。

我使用的依赖是:

<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>

现在我发现 JDK 版本是这里唯一的问题。

在 Windows 上我有 JDK 1.7,而在 MAC 上我有 JDK 1.6。 这真的是 JDK 问题吗,因为我真的被困在这里了。

请帮忙。

最佳答案

我在 Linux 中看到了不同的值。我认为原因是 SecureRandom,请检查一下:

System.out.println(new SecureRandom("admin".getBytes()).nextLong());
System.out.println(new SecureRandom("admin".getBytes()).nextLong());

示例输出(每次都会更改):

1642139269925848082
2081201540941864354

来自javadoc:

Many SecureRandom implementations are in the form of a pseudo-random number generator (PRNG), which means they use a deterministic algorithm to produce a pseudo-random sequence from a true random seed. Other implementations may produce true random numbers, and yet others may use a combination of both techniques.

关于java - 使用 byte[] 生成 key 会为 MAC 和 Windows 生成不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21900995/

相关文章:

java - 使用带有 Swing 组件的 RMI 代理时性能不佳

java - 哈多普 : datanode not running?

java - 我应该使用哪种设计模式来存储集合?

c++ - 在 windows 下构建(和运行)RInside 示例

windows - 从哪里开始使用 Direct2d?

ios - 在 iPhone 模拟器中,如何在带有德语键盘的 macbook 上输入 @ 符号?

java - 如何使用 JEval 库评估 java 中的幂、根、阶乘函数?

c++ - C++比较两个文件

macos - Mac App Store 中使用 Safari 组件的应用程序的导出合规性

ios - 在 macOS 编程中是否有 UIGraphicsGetImageFromCurrentImageContext() 的替代方法?