C#RijndaelManaged加密存储密钥

时间:2014-07-29 16:49:01

标签: c# encryption rijndaelmanaged

我的疑问是关于解密加密字符串的关键,没有用于加密字符串的相同密钥我没有得到原始字符串确定,但我需要保护此密钥而不是在硬编码中使用她,因为任何黑客都可以反编译dll并看到这个密钥,如果我将此密钥存储在任何存档中,黑客可以复制此存档和我的方法并解密我的文本,我该如何防止这种攻击?在我的代码实现之后,这里的盐和密钥是静态的我试图以任何方式思考以保护这些数据

    private static byte[] salt = new byte[255];
    private static byte[] key;
    internal static string EncryptString(string InputText)
    {
        System.Security.Cryptography.RijndaelManaged RijndaelCipher = 
            new System.Security.Cryptography.RijndaelManaged();

        RNGCryptoServiceProvider rcs = new RNGCryptoServiceProvider();
        rcs.GetBytes(salt);

        key = RijndaelCipher.Key;
        byte[] plainText = System.Text.Encoding.Unicode.GetBytes(InputText); 

        System.Security.Cryptography.PasswordDeriveBytes SecretKey =
            new System.Security.Cryptography.PasswordDeriveBytes(RijndaelCipher.Key, salt);

        System.Security.Cryptography.ICryptoTransform Encryptor = 
            RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

        System.Security.Cryptography.CryptoStream cryptoStream = 
            new System.Security.Cryptography.CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(plainText, 0, plainText.Length);

        cryptoStream.FlushFinalBlock();
        byte[] CipherBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        string EncryptedData = Convert.ToBase64String(CipherBytes);
        return EncryptedData;

    }

    internal static string DecryptString(string text)
    {

        System.Security.Cryptography.RijndaelManaged RijndaelCipher = 
            new System.Security.Cryptography.RijndaelManaged();

        byte[] EncryptedData = Convert.FromBase64String(text);

        System.Security.Cryptography.PasswordDeriveBytes SecretKey =
            new System.Security.Cryptography.PasswordDeriveBytes(RijndaelCipher.Key, salt);

        ICryptoTransform Decryptor = 
            RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(EncryptedData);

        CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
        byte[] PlainText = new byte[EncryptedData.Length];
        int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
        memoryStream.Close();
        cryptoStream.Close();

        string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
        return DecryptedData;

    }


    #endregion


}    

0 个答案:

没有答案