2 回答

TA貢獻1735條經驗 獲得超5個贊
密文不同,因為PasswordDeriveBytes
在 C# 代碼和PBKDF2WithHmacSHA1
Java 代碼中生成不同的密鑰:
PBKDF2WithHmacSHA1
顧名思義,它是使用 SHA-1的 PBKDF 2的實現。的實現
PasswordDeriveBytes
基于 PBKDF 1,但增加了一些擴展。
除了 C#-type 之外PasswordDeriveBytes
,還有 C#-type Rfc2898DeriveBytes
,它是 PBKDF2 的實現,帶有 SHA-1,因此PBKDF2WithHmacSHA1
與 Java 代碼中的對應。
如果可能,Rfc2898DeriveBytes
應該在 C# 代碼中使用 代替PasswordDeriveBytes
,例如參見此處或此處的PBKDF2部分。然后兩個代碼返回相同的密文。
據我所知,沒有提供 C#-type 的 Java 實現的提供程序PasswordDeriveBytes
。但是,Internet 上有功能相同的 Java 實現,例如這里。如果 Java 代碼使用這樣的實現而不是PBKDF2WithHmacSHA1
,則兩個代碼都返回相同的密文。但正如已經提到的,這應該是第二選擇。

TA貢獻1829條經驗 獲得超13個贊
正如下面所承諾的那樣是解決方案 - 再次感謝您的支持
public static class Encryption
{
public static string Encrypt(string text)
{
var thePassword = "%cFRm*F)N9Rq[6#5";
byte[] IV = Encoding.UTF8.GetBytes("7!,V5u]Bu>q>7zY'");
var md5 = new MD5CryptoServiceProvider();
var password = md5.ComputeHash(Encoding.ASCII.GetBytes(thePassword));
var cipher = new RijndaelManaged();
var encryptor = cipher.CreateEncryptor(password, IV);
var buffer = Encoding.ASCII.GetBytes(text);
return Convert.ToBase64String(encryptor.TransformFinalBlock(buffer, 0, buffer.Length));
}
public static string Decrypt(string text)
{
var thePassword = "%cFRm*F)N9Rq[6#5";
byte[] IV = Encoding.UTF8.GetBytes("7!,V5u]Bu>q>7zY'");
var md5 = new MD5CryptoServiceProvider();
var password = md5.ComputeHash(Encoding.ASCII.GetBytes(thePassword));
var cipher = new RijndaelManaged();
var decryptor = cipher.CreateDecryptor(password, IV);
byte[] input = Convert.FromBase64String(text);
var newClearData = decryptor.TransformFinalBlock(input, 0, input.Length);
return Encoding.ASCII.GetString(newClearData);
}
}
和java等價物
public class Encryption {
public static String Encrypt(String str)
{
try
{
String thePassword = "%cFRm*F)N9Rq[6#5";
byte[] encryptedData;
byte[] IV = "7!,V5u]Bu>q>7zY'".getBytes();
MessageDigest digest = MessageDigest.getInstance("MD5");
SecretKeySpec password = new SecretKeySpec(digest.digest(thePassword.getBytes()), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec IVParamSpec = new IvParameterSpec(IV);
cipher.init(Cipher.ENCRYPT_MODE, password, IVParamSpec);
encryptedData = cipher.doFinal(str.getBytes());
return DatatypeConverter.printBase64Binary(encryptedData);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String Decrypt(String str)
{
try
{
String thePassword = "%cFRm*F)N9Rq[6#5";
byte[] encryptedData = DatatypeConverter.parseBase64Binary(str);
byte[] IV = "7!,V5u]Bu>q>7zY'".getBytes();
MessageDigest digest = MessageDigest.getInstance("MD5");
SecretKeySpec password = new SecretKeySpec(digest.digest(thePassword.getBytes()), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec IVParamSpec = new IvParameterSpec(IV);
cipher.init(Cipher.DECRYPT_MODE, password, IVParamSpec);
byte[] decryptedVal = cipher.doFinal(encryptedData);
return new String(decryptedVal);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
添加回答
舉報