【发布时间】:2013-09-27 12:42:54
【问题描述】:
我有这个 C# 代码来加密/解密字符串:
private static byte[] EncryptString(byte[] clearText, byte[] Key, byte[] IV)
{
MemoryStream ms = new MemoryStream();
Rijndael alg = Rijndael.Create();
alg.Key = Key;
alg.IV = IV;
CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearText, 0, clearText.Length);
cs.Close();
byte[] encryptedData = ms.ToArray();
return encryptedData;
}
public static string EncryptString(string clearText, string Password)
{
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x74, 0x68, 0x69, 0x73, 0x69, 0x61, 0x74, 0x65, 0x73, 0x74 });
byte[] encryptedData = EncryptString(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
return Convert.ToBase64String(encryptedData);
}
private static byte[] DecryptString(byte[] cipherData, byte[] Key, byte[] IV)
{
MemoryStream ms = new MemoryStream();
Rijndael alg = Rijndael.Create();
alg.Key = Key;
alg.IV = IV;
CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherData, 0, cipherData.Length);
cs.Close();
byte[] decryptedData = ms.ToArray();
return decryptedData;
}
public static string DecryptString(string cipherText, string Password)
{
if (!string.IsNullOrEmpty(cipherText))
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x74, 0x68, 0x69, 0x73, 0x69, 0x61, 0x74, 0x65, 0x73, 0x74 });
byte[] decryptedData = DecryptString(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
return System.Text.Encoding.Unicode.GetString(decryptedData);
}
else
{
return "";
}
}
加密的字符串应该本地存储在注册表或文件中。 Delphi 应用程序也必须有权访问此字符串。请注意,由于某种原因,无法将加密/解密代码外包给 DLL。
我的问题是我无法在 Delphi 中生成“PasswordDerivedBytes”。 有人可以给我一个提示吗?
【问题讨论】:
-
不幸的是,StackOverflow 不能将您的代码从一种语言转换为另一种语言。您需要自己进行研究并自己进行,当您遇到特定问题时,请询问该特定问题。
-
有很多 Rijndael 实现。找到一个并使用它。
-
很抱歉以不当方式提出我的问题。是的,您是对的,您可能会有这样的印象,即我希望将我的代码从 C# 转换为 Delphi,但这不是我的意图。请让我澄清我的问题:我的特殊问题是我无法在 Delphi 中获得“PasswordDerivedBytes”的对应项。因此我无法在 Delphi 中得到正确的结果。你能告诉我如何在 Delphi 中构建 PasswordDerivedBytes 吗?
-
请在问题中填写详细信息,而不是 cmets。编辑问题。
-
PasswordDerivedBytes必须是您发布的代码专有的类型,但您的代码不包含此内容。你确定这是所有代码吗?
标签: c# delphi encryption cryptography