Java中的PBKDF2和Bouncy Castle与.NET Rfc2898DeriveBytes?
|
我有一些使用PBKDF2生成密钥的C#代码。
//byte[] salt = new RNGCryptoServiceProvider().GetBytes(salt);
byte[] salt = new byte[] { 19, 3, 248, 189, 144, 42, 57, 23 }; // for testing
byte[] bcKey = new Rfc2898DeriveBytes(\"mypassword\", salt, 8192).GetBytes(32);
这很好。我正在尝试使用Bouncy Castle在Java中实现相同的功能。无法使其正常工作(Java缺少无符号类型的事实使它更加烦人)。
SecureRandom random = new SecureRandom();
byte[] salt = u2s(new int[] { 19, 3, 248, 189, 144, 42, 57, 23 });
//random.nextBytes(salt);
PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes((\"BLK\" + password).toCharArray()), salt, keyTransformationRounds);
KeyParameter params = (KeyParameter)generator.generateDerivedParameters(keyLengthBits);
byte[] bcKey = params.getKey();
int[] bcKeyU = s2u(bcKey);
System.out.println(new String(Base64.encode(bcKey), \"UTF-8\"));
// Helper functions because Java has no unsigned types
//
// EDIT: THESE FUNCTIONS ARE INCORRECT.
// See my answer below for the correct versions.
//
static byte[] u2s(int[] unsignedArray) throws IOException
{
byte[] signedArray = new byte[unsignedArray.length];
for (int i = 0; i < signedArray.length; i++)
{
if (unsignedArray[i] < 0 || unsignedArray[i] > 255)
{
throw new IOException(\"unsignedArray at \" + i + \" was not within the range 0 to 255.\");
}
signedArray[i] = (byte)(unsignedArray[i] - 128);
}
return signedArray;
}
static int[] s2u(byte[] signedArray)
{
int[] unsignedArray = new int[signedArray.length];
for (int i = 0; i < unsignedArray.length; i++)
{
unsignedArray[i] = (int)(signedArray[i] + 128);
}
return unsignedArray;
}
结果bcKey字节数组不同。我究竟做错了什么?我要处理从未签名到已签名的转换,还是不能按预期工作?
没有找到相关结果
已邀请:
1 个回复
荤碗
中0-255范围之外的整数,但可能有助于调试。