簡體   English   中英

如何在Delphi和C#中加密數據以使它們兼容?

[英]How can I encrypt data in Delphi and in C# so that they are compatible?

我想以一種與我服務器上的加密兼容的方式在我的Delphi應用程序中加密客戶端上的一些數據。 在我的服務器上,我使用這個C#代碼加密數據:

public class AesCryptUtils
{

    private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");

    /// <summary> 
    /// Encrypt the given string using AES.  The string can be decrypted using  
    /// DecryptStringAES().  The sharedSecret parameters must match. 
    /// </summary> 
    /// <param name="plainText">The text to encrypt.</param> 
    /// <param name="sharedSecret">A password used to generate a key for encryption.</param> 
    public static string EncryptStringAES(string plainText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(plainText))
            throw new ArgumentNullException("plainText");
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        string outStr = null;                       // Encrypted string to return 
        AesManaged aesAlg = null;              // AesManaged object used to encrypt the data. 

        try
        {
            // generate the key from the shared secret and the salt 
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

            // Create a AesManaged object 
            // with the specified key and IV. 
            aesAlg = new AesManaged();
            aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
            aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

            // Create a decrytor to perform the stream transform. 
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption. 
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream. 
                        swEncrypt.Write(plainText);
                    }
                }
                outStr = Convert.ToBase64String(msEncrypt.ToArray());
            }
        }
        finally
        {
            // Clear the AesManaged object. 
            if (aesAlg != null)
                aesAlg.Clear();
        }

        // Return the encrypted bytes from the memory stream. 
        return outStr;
    }
}

如何在Delphi中實現這種加密算法? 給定相同的輸入,得到的加密數據必須相同。

您的問題的相關問題列表包含此鏈接 ,其中提到了Delphi的一些AES實現。 我相信你可以找到更多,你總是可以使用像OpenSSL或CryptoAPI這樣的東西,但你可能需要自己編寫Delphi綁定。

請注意,由於您未直接傳遞密鑰,因此您還需要實現密鑰派生。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM