繁体   English   中英

等效于Delphi中的C#加密/解密代码

[英]An equivalent of C# encryption/decryption code in Delphi

我有以下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”。 有人可以给我一个提示如何工作吗?

我建议您使用Delphi Encryption Compedium 它几乎具有您需要加密的所有内容,并且拥有一些大多数可以完成您想做的事的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM