【发布时间】:2010-05-31 08:15:08
【问题描述】:
我们有一个用 Delphi 编写的项目,我们想将其转换为 C#。问题是我们有一些密码和设置被加密并写入注册表。当我们需要一个指定的密码时,我们从注册表中获取它并解密它以便我们可以使用它。对于转换为 C#,我们必须以相同的方式执行此操作,以便拥有旧版本并想要升级它的用户也可以使用该应用程序。
这是我们在 Delphi 中用于加密/解密字符串的代码:
unit uCrypt;
interface
function EncryptString(strPlaintext, strPassword : String) : String;
function DecryptString(strEncryptedText, strPassword : String) : String;
implementation
uses
DCPcrypt2, DCPblockciphers, DCPdes, DCPmd5;
const
CRYPT_KEY = '1q2w3e4r5t6z7u8';
function EncryptString(strPlaintext) : String;
var
cipher : TDCP_3des;
strEncryptedText : String;
begin
if strPlaintext <> '' then
begin
try
cipher := TDCP_3des.Create(nil);
try
cipher.InitStr(CRYPT_KEY, TDCP_md5);
strEncryptedText := cipher.EncryptString(strPlaintext);
finally
cipher.Free;
end;
except
strEncryptedText := '';
end;
end;
Result := strEncryptedText;
end;
function DecryptString(strEncryptedText) : String;
var
cipher : TDCP_3des;
strDecryptedText : String;
begin
if strEncryptedText <> '' then
begin
try
cipher := TDCP_3des.Create(nil);
try
cipher.InitStr(CRYPT_KEY, TDCP_md5);
strDecryptedText := cipher.DecryptString(strEncryptedText);
finally
cipher.Free;
end;
except
strDecryptedText := '';
end;
end;
Result := strDecryptedText;
end;
end.
例如,当我们要加密字符串asdf1234 时,我们会得到WcOb/iKo4g8= 的结果。
我们现在要在 C# 中解密该字符串。这是我们尝试做的:
public static void Main(string[] args)
{
string Encrypted = "WcOb/iKo4g8=";
string Password = "1q2w3e4r5t6z7u8";
string DecryptedString = DecryptString(Encrypted, Password);
}
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
// Step 1. We hash the passphrase using MD5
// We use the MD5 hash generator as the result is a 128 bit byte array
// which is a valid length for the TripleDES encoder we use below
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
// Step 2. Create a new TripleDESCryptoServiceProvider object
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
// Step 3. Setup the decoder
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.None;
// Step 4. Convert the input string to a byte[]
byte[] DataToDecrypt = Convert.FromBase64String(Message);
// Step 5. Attempt to decrypt the string
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
// Clear the TripleDes and Hashprovider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
// Step 6. Return the decrypted string in UTF8 format
return UTF8.GetString(Results);
}
结果与预期结果不同。在我们调用DecryptString() 之后,我们希望得到asdf1234,但我们得到了其他东西。
有人知道如何正确解密吗?
提前致谢
西蒙
编辑:
好的,谢谢大家的建议。我们无法找到如何在 C# 中完成这一切,因此我们决定采用我们的后备版本,使用带有 P/Invoke 的 Delphi DLL,正如建议的那样。
【问题讨论】:
标签: c# delphi encryption