在C#中对数据进行加密 [英] Encrypting data in C#

查看:126
本文介绍了在C#中对数据进行加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要,然后存储在文件中的数据进行加密的应用程序。此数据应被加密,以一个工业标准如AES。
中的数据可以是文本或二进制数据。



而不是某处存储密钥,用户应该提供一个字母数字密码(用作键)来解密数据。



什么是去了解这在C#.NET 3.5的最佳方式?理想的情况是我在找一个黑盒类,我可以使用像这样:

 字节[] = writeThisToFile EncryptionClass.Encrypt(串数据串密码); 

字节[] = writeThisToFile EncryptionClass.Encrypt(字节[]数据,串密码);

字节[] = plainBinaryData EncryptionClass.DecryptBinary(字节[] encryptedFileContents,字符串密码);

字符串明文= EncryptionClass.DecryptText(字节[] encryptedFileContents,字符串密码);


解决方案

 使用系统.IO; 
使用System.Security;
使用System.Security.Cryptography;使用System.Runtime.InteropServices
;

//<总结>
//加密字符串
//< /总结>
//< PARAM NAME =密文>文字进行加密< /参数>
//< PARAM NAME =密码>密码以<进行加密; /参数>
//&下; PARAM NAME =盐>盐至以<加密/参数>
//< PARAM NAME =的HashAlgorithm>既可以是SHA1或MD5< /参数>
//< PARAM NAME =PasswordIterations>反复做<的数目; /参数>
//< PARAM NAME =InitialVector>需要进行长期< 16个ASCII字符; /参数>
//< PARAM NAME =密钥长度>可以是128,192,或256< /参数>
//<返回>一种解密的字符串< /回报>
公共静态字符串AESEncrypt(字符串明文字符串密码,串盐,字符串的HashAlgorithm,诠释PasswordIterations,串InitialVector,诠释密钥大小)
{
如果(string.IsNullOrEmpty(明文))
{
回报一文由AES被Decryped不能为空......;
}
,否则如果(string.IsNullOrEmpty(密码))
{
回报为AES解密密码不能为空。;
}
字节[] = InitialVectorBytes Encoding.ASCII.GetBytes(InitialVector);
字节[] = SaltValueBytes Encoding.ASCII.GetBytes(盐);
字节[] = PlainTextBytes Encoding.UTF8.GetBytes(明文);
PasswordDeriveBytes DerivedPassword =新PasswordDeriveBytes(密码,SaltValueBytes,的HashAlgorithm,PasswordIterations);
字节[] = KeyBytes DerivedPassword.GetBytes(密钥/ 8);

RijndaelManaged的SymmetricKey =新RijndaelManaged的();

SymmetricKey.Mode = CipherMode.CBC;

字节[] CipherTextBytes = NULL;使用(ICryptoTransform的加密器= SymmetricKey.CreateEncryptor(KeyBytes,InitialVectorBytes))
{
$ B $使用B

(MemoryStream的MemStream =新的MemoryStream())
{
使用(CryptoStream的CryptoStream的=新的CryptoStream(MemStream,加密机,CryptoStreamMode.Write))
{
CryptoStream.Write(PlainTextBytes,0,PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
CipherTextBytes = MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
返回Convert.ToBase64String(CipherTextBytes);

}


//<总结>
//解密字符串
//< /总结>
//< PARAM NAME =密文>文字进行解密< /参数>
//< PARAM NAME =密码>密码以<解密; /参数>
//&下; PARAM NAME =盐>盐至以<解密; /参数>
//< PARAM NAME =的HashAlgorithm>既可以是SHA1或MD5< /参数>
//< PARAM NAME =PasswordIterations>反复做<的数目; /参数>
//< PARAM NAME =InitialVector>需要进行长期< 16个ASCII字符; /参数>
//< PARAM NAME =密钥长度>可以是128,192,或256< /参数>
//<返回>一种解密的字符串< /回报>
公共静态字符串AESDecrypt(密文字符串,字符串密码,串盐,字符串的HashAlgorithm,诠释PasswordIterations,串InitialVector,诠释密钥大小)
{
如果(string.IsNullOrEmpty(密文))
{
回报一文由AES被Decryped不能为空......;
}
,否则如果(string.IsNullOrEmpty(密码))
{
回报为AES解密密码不能为空。;
}
字节[] = InitialVectorBytes Encoding.ASCII.GetBytes(InitialVector);
字节[] = SaltValueBytes Encoding.ASCII.GetBytes(盐);
字节[] = CipherTextBytes Convert.FromBase64String(密文);
PasswordDeriveBytes DerivedPassword =新PasswordDeriveBytes(密码,SaltValueBytes,的HashAlgorithm,PasswordIterations);
字节[] = KeyBytes DerivedPassword.GetBytes(密钥/ 8);
RijndaelManaged的SymmetricKey =新RijndaelManaged的();
SymmetricKey.Mode = CipherMode.CBC;
字节[] = PlainTextBytes新的字节[CipherTextBytes.Length]
INT BYTECOUNT = 0;

{
$ B $使用B(ICryptoTransform的解密= SymmetricKey.CreateDecryptor(KeyBytes,InitialVectorBytes))
{使用(MemoryStream的MemStream =新的MemoryStream(CipherTextBytes
))
{使用
(CryptoStream的CryptoStream的=新的CryptoStream(MemStream,解密,CryptoStreamMode.Read))
{
BYTECOUNT = CryptoStream.Read(PlainTextBytes,0,PlainTextBytes.Length );
MemStream.Close();
CryptoStream.Close();
}
}
}
}
赶上(例外五)
{
返回请输入正确的密码和盐... +出现下列错误:+/ N+ E;
}
SymmetricKey.Clear();
返回Encoding.UTF8.GetString(PlainTextBytes,0,BYTECOUNT);

}



不记得确切位置,我从后天这段代码,但我改变了它返回的加密结果为字符串。这些方法可以很容易地包裹成FileEncryptor类。虽然我相信有更好的解决方案有...


I have an application that needs to encrypt data which is then stored in files. This data should be encrypted to an industry standard such as AES. The data may be either text or binary data.

Rather than store the key somewhere, the user should supply an alphanumeric password (used as the key) to decrypt the data.

What is the best way to go about this in C# .NET 3.5? Ideally I am looking for a black box class that I can use like so:

byte[] writeThisToFile = EncryptionClass.Encrypt(string data, string password);

byte[] writeThisToFile = EncryptionClass.Encrypt(byte[] data, string password);

byte[] plainBinaryData = EncryptionClass.DecryptBinary(byte[] encryptedFileContents, string password);

string plainText = EncryptionClass.DecryptText(byte[] encryptedFileContents, string password);

解决方案

    using System.IO;
    using System.Security;
    using System.Security.Cryptography;
    using System.Runtime.InteropServices;   

    // <summary>  
    // Encrypts a string          
    // </summary>        
    // <param name="CipherText">Text to be Encrypted</param>         
    // <param name="Password">Password to Encrypt with</param>         
    // <param name="Salt">Salt to Encrypt with</param>          
    // <param name="HashAlgorithm">Can be either SHA1 or MD5</param>         
    // <param name="PasswordIterations">Number of iterations to do</param>          
    // <param name="InitialVector">Needs to be 16 ASCII characters long</param>          
    // <param name="KeySize">Can be 128, 192, or 256</param>          
    // <returns>A decrypted string</returns>       
    public static string AESEncrypt(string PlainText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize)
    {
        if (string.IsNullOrEmpty(PlainText))
        {
            return "The Text to be Decryped by AES must not be null...";
        }
        else if (string.IsNullOrEmpty(Password))
        {
            return "The Password for AES Decryption must not be null...";
        }
        byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
        byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
        byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
        PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
        byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);

        RijndaelManaged SymmetricKey = new RijndaelManaged();

        SymmetricKey.Mode = CipherMode.CBC;

        byte[] CipherTextBytes = null;

        using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
        {

            using (MemoryStream MemStream = new MemoryStream())
            {
                using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                {
                    CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                    CryptoStream.FlushFinalBlock();
                    CipherTextBytes = MemStream.ToArray();
                    MemStream.Close();
                    CryptoStream.Close();
                }
            }
        }
        SymmetricKey.Clear();
        return Convert.ToBase64String(CipherTextBytes);

    }


    // <summary>  
    // Decrypts a string          
    // </summary>        
    // <param name="CipherText">Text to be decrypted</param>         
    // <param name="Password">Password to decrypt with</param>         
    // <param name="Salt">Salt to decrypt with</param>          
    // <param name="HashAlgorithm">Can be either SHA1 or MD5</param>         
    // <param name="PasswordIterations">Number of iterations to do</param>          
    // <param name="InitialVector">Needs to be 16 ASCII characters long</param>          
    // <param name="KeySize">Can be 128, 192, or 256</param>          
    // <returns>A decrypted string</returns>        
    public static string AESDecrypt(string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize)
    {
        if (string.IsNullOrEmpty(CipherText))
        {
            return "The Text to be Decryped by AES must not be null...";
        }
        else if (string.IsNullOrEmpty(Password))
        {
            return "The Password for AES Decryption must not be null...";
        }
        byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
        byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
        byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
        PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
        byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
        RijndaelManaged SymmetricKey = new RijndaelManaged();
        SymmetricKey.Mode = CipherMode.CBC;
        byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
        int ByteCount = 0;
        try
        {

            using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                    {
                        ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
        }
        catch (Exception e)
        {
            return "Please Enter the Correct Password and Salt..." + "The Following Error Occured: " + "/n" + e;
        }
        SymmetricKey.Clear();
        return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);

    }

Can't Remember exactly where I acquired this code from, but I altered it to return the encrypted Result as a string. These Methods could easily be wrapped into a FileEncryptor Class. Although I am sure there are better solutions out there...

这篇关于在C#中对数据进行加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆