如何解密通过.Net代码加密的SQL Server中的列

时间:2019-07-19 17:34:53

标签: c# sql-server encryption

我想创建一个存储过程,以解密由.Net库加密的列。

这是用于加密数据的C#代码:

public static byte[] Encrypt(string plainText, byte[] salt, byte[] key)
{
    using (var aesManaged = new AesManaged())
    {
        if (key.Length != aesManaged.Key.Length)    // I use this to toggle encryption on/off
            return Encoding.UTF8.GetBytes(plainText);

        if (salt.Length == 0)
            throw new ArgumentException("salt.Length must be > 0");

        byte[] hash;
        using (var sha = SHA256.Create())
            hash = sha.ComputeHash(salt);

        byte[] iv = new byte[aesManaged.IV.Length];
        if (hash.Length < iv.Length)
            throw new IndexOutOfRangeException("Hash algorithm returns too few bytes for use as IV for encryption algorithm");
        else
            Buffer.BlockCopy(hash, 0, iv, 0, iv.Length);

        using (var encryptor = aesManaged.CreateEncryptor(key, iv))
        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            using (var streamWriter = new StreamWriter(cryptoStream))
                streamWriter.Write(plainText);
            return Concatenate(iv, memoryStream.ToArray());
        }
    }
}

这是将在SQL Server中加载以由存储过程调用的C#代码:

[SqlProcedure]
public static string SLWSDecrypt(string protectedData, string key)
{
    byte[] keyArray = FromHexString(key);
    byte[] cryptogram = Convert.FromBase64String(protectedData.ToString());

    using (var aesManaged = new AesManaged())
    {
        if (key.Length != aesManaged.Key.Length)    // I use this to toggle encryption on/off
            return Encoding.UTF8.GetString(cryptogram);

        byte[] iv;
        byte[] encryptedData;
        int ivLen = aesManaged.IV.Length;

        Split(cryptogram, ivLen, out iv, out encryptedData);

        using (var decryptor = aesManaged.CreateDecryptor(keyArray, iv))
        using (var memoryStream = new MemoryStream(encryptedData))
        {
            using (var decryptStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
            using (var decryptReader = new StreamReader(decryptStream))
                return decryptReader.ReadToEnd();
        }
    }
}

这是程序集的注册:

CREATE ASSEMBLY MyEncryptor FROM 'C:\MyAssemblies\MyEncryptor.dll' WITH PERMISSION_SET = SAFE
GO

CREATE PROCEDURE SLWSDecrypt
    @dataToDecrypt VARCHAR(MAX), 
    @key VARCHAR(32),
    @decryptedText VARCHAR(MAX) OUTPUT
    AS 
    EXTERNAL NAME MyEncryptor.MyEncryption.SLWSDecrypt
GO

尝试运行CREATE PROCEDURE语句时遇到的错误:

  

CREATE PROCEDURE失败,因为只能在返回SqlInt32,System.Int32,System.Nullable,void的CLR方法上定义CLR过程。

0 个答案:

没有答案