我正在尝试在 C# 中复制此 Java 代码。
BASE64Decoder dec = new BASE64Decoder();
byte[] salt = null;
try {
salt = dec.decodeBuffer(saltStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Security.insertProviderAt(new BouncyCastleProvider(), 1);
String alg = "PBEWITHSHA256AND256BITAES-CBC-BC";
int derivedKeyLength = 256;
int iterations = 20000;
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations,
derivedKeyLength);
try {
SecretKeyFactory f = SecretKeyFactory.getInstance(alg);
byte[] result = f.generateSecret(spec).getEncoded();
BASE64Encoder endecoder = new BASE64Encoder();
System.out.println(endecoder.encode(result));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是我到目前为止所拥有的,但它失败了。我是加密世界的新手(所以可能有一种我不知道的更简单的方法)所以任何帮助将不胜感激。谢谢!
var iterations = 20000;
PbeParametersGenerator pGen = new Pkcs12ParametersGenerator(new Sha256Digest());
pGen.Init(Encoding.ASCII.GetBytes(password), Convert.FromBase64String(salt), iterations);
ICipherParameters par = pGen.GenerateDerivedParameters("AES256", 256);
IBufferedCipher c = CipherUtilities.GetCipher("PBEWITHSHA256AND256BITAES-CBC-BC");
Console.WriteLine(c.AlgorithmName);
c.Init(true, par);
byte[] enc = c.DoFinal(Convert.FromBase64String(salt));
Console.WriteLine("The output is :");
Console.WriteLine(Convert.ToBase64String(enc));
问题在于,在 Java 和 C# 中,使用相同的密码、相同的盐和相同的迭代次数时,加密的结果是不一样的。
更新:
问题是Java代码(不是我写的,没有进行密码加密)它只生成密钥参数。此代码将提供与 Java 代码相同的输出。
var iterations = 20000;
var sltBytes = Convert.FromBase64String(salt);
byte[] byteSalt = Convert.FromBase64String(salt);
byte[] pwdb = PbeParametersGenerator.Pkcs12PasswordToBytes(password.ToCharArray());
PbeParametersGenerator pGen = new Pkcs12ParametersGenerator(new Sha256Digest());
pGen.Init(pwdb, Convert.FromBase64String(salt), iterations);
var par = (ParametersWithIV)pGen.GenerateDerivedParameters("AES256", 256, 128);
var kpar = (KeyParameter)par.Parameters;
byte[] by = kpar.GetKey();
Console.WriteLine(Convert.ToBase64String(by));