简体   繁体   中英

An equivalent of C# encryption/decryption code in Delphi

I've got this C# code to encrypt/decrypt strings:

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 "";
    }
}

Encrypted strings should be stored locally in the registry or a file. A Delphi application has to have access to this strings too. Please note that, for some reason, it is not possible to outsource the encryption/decryption code to a DLL.

My Problem is that i am not able to produce "PasswordDerivedBytes" in Delphi. Can somebody please give me a hint how that can work?

I would suggest to you to use the Delphi Encryption Compedium . It has almost anything you need cryptowise and hase some examples which mostly do what you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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