使用C#和SQL Server加密和解密数据

时间:2011-10-27 20:28:15

标签: c# asp.net sql-server-2005

我想用C#创建一个ASP.Net应用程序,我将在SQL Server 2005上存储数据,这些数据将被加密我想找到一个算法用C#加密数据并在SQL服务端解密它我想用SQL加密一些数据并用C#解密它是什么最好的算法?

private byte[] key = {
    0x61,
    0x72,
    0x84,
    0x7a,
    0x24,
    0x43,
    0x65,
    0x64,
    0x73,
    0x55,
    0x64,
    0x75,
    0x66

};



const string PASSWORD = "TestPassword";
public object Encrypt(string sPlainText)
{



    byte[] aPlainBytes = null;

    PasswordDeriveBytes aPassword = default(PasswordDeriveBytes);



    aPlainBytes = System.Text.Encoding.Unicode.GetBytes(sPlainText);

    aPassword = new PasswordDeriveBytes(PASSWORD, key);

    byte[] sEncryptedData = Encrypt(aPlainBytes, aPassword.GetBytes(32), aPassword.GetBytes(16));

    //' MessageBox.Show(Convert.ToString(sEncryptedData.ToString))

    return Convert.ToBase64String(sEncryptedData);



}



private byte[] Encrypt(byte[] sPlainData, byte[] aKey, byte[] aIV)
{



    MemoryStream oMemoryStream = new MemoryStream();



    Rijndael oRijndael = Rijndael.Create();

    oRijndael.Key = aKey;



    oRijndael.IV = aIV;



    CryptoStream oCryptoStream = new CryptoStream(oMemoryStream, oRijndael.CreateEncryptor(), CryptoStreamMode.Write);

    oCryptoStream.Write(sPlainData, 0, sPlainData.Length);

    oCryptoStream.Close();

    byte[] aEncryptedData = oMemoryStream.ToArray();




    return aEncryptedData;



}

2 个答案:

答案 0 :(得分:5)

C#: System.Security.Cryptography

SQL Server: Sql Server Encryption

来自here

C#示例

private static void EncryptData(String inName, String outName, byte[] tdesKey, byte[] tdesIV)
{    
    //Create the file streams to handle the input and output files.
    FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
    FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
    fout.SetLength(0);

    //Create variables to help with read and write.
    byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
    long rdlen = 0;              //This is the total number of bytes written.
    long totlen = fin.Length;    //This is the total length of the input file.
    int len;                     //This is the number of bytes to be written at a time.

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();          
    CryptoStream encStream = new CryptoStream(fout, tdes.CreateEncryptor(tdesKey, tdesIV), CryptoStreamMode.Write);

    Console.WriteLine("Encrypting...");

    //Read from the input file, then encrypt and write to the output file.
    while(rdlen < totlen)
    {
        len = fin.Read(bin, 0, 100);
        encStream.Write(bin, 0, len);
        rdlen = rdlen + len;
        Console.WriteLine("{0} bytes processed", rdlen);
    }

    encStream.Close();                     
}
来自here

SQL Server示例

USE AdventureWorks2008R2;
GO

--If there is no master key, create one now. 
IF NOT EXISTS 
    (SELECT * FROM sys.symmetric_keys WHERE symmetric_key_id = 101)
    CREATE MASTER KEY ENCRYPTION BY 
    PASSWORD = '23987hxJKL969#ghf0%94467GRkjg5k3fd117r$$#1946kcj$n44nhdlj'
GO

CREATE CERTIFICATE HumanResources037
   WITH SUBJECT = 'Employee Social Security Numbers';
GO

CREATE SYMMETRIC KEY SSN_Key_01
    WITH ALGORITHM = AES_256
    ENCRYPTION BY CERTIFICATE HumanResources037;
GO

USE [AdventureWorks2008R2];
GO

-- Create a column in which to store the encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber varbinary(128); 
GO

-- Open the symmetric key with which to encrypt the data.
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;

-- Encrypt the value in column NationalIDNumber with symmetric 
-- key SSN_Key_01. Save the result in column EncryptedNationalIDNumber.
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber = EncryptByKey(Key_GUID('SSN_Key_01'), NationalIDNumber);
GO

-- Verify the encryption.
-- First, open the symmetric key with which to decrypt the data.
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;
GO

-- Now list the original ID, the encrypted ID, and the 
-- decrypted ciphertext. If the decryption worked, the original
-- and the decrypted ID will match.
SELECT NationalIDNumber, EncryptedNationalIDNumber 
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalIDNumber)) 
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
GO

答案 1 :(得分:0)

C#和SQL都可以使用三重DES加密方法,但我可能会选择一个位置来执行这两种方法。除非你出于某种原因要求两者都预先形成它。请参阅this示例,了解如何在SQL级别使用加密