我正在尝试使用 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/