SQL CLR使用RijndaelManaged解密字符串值的函数

时间:2014-04-15 19:13:08

标签: c# sql-server encryption sqlclr rijndaelmanaged

我尝试创建一个clr帮助函数来显示db中某些加密数据的纯文本值。下面是函数,你看到的解密代码(第二和第三种方法)在非clr代码中成功使用,但在这里它失败了,有着名的"填充无效,无法删除。"错误。加密端完全用c#代码和插入db的加密字符串值完成。我用无意义的字符串fyi替换了键和盐。数据存储在nvarchar列中。任何人都有任何线索出错?

重申一下,相同的代码(第二和第三种方法)在sql clr函数之外工作,但不能在这里工作。

using System.Data.Sql;
using System.IO;
using System.Security.Cryptography;
using System.Data.SqlTypes;
using System.Text;
using Microsoft.SqlServer.Server;
using System.Data.SqlClient;

public class Functions
{
    private static byte[] _Key { get { return System.Text.Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz"); } }
    private static byte[] _IV { get { return System.Text.Encoding.ASCII.GetBytes("abcdefghijklmn"); } }

    [SqlFunction(IsDeterministic = true, IsPrecise = true, DataAccess = DataAccessKind.None)]
    public static string Decrypt(SqlString value)
    {
        return _Decrypt(value.ToString(), _Key, _IV);
    }

    public static string _Decrypt(string encryptedString, byte[] key, byte[] iv)
    {
        if (string.IsNullOrEmpty(encryptedString))
        {
            return null;
        }

        using (RijndaelManaged rijndael = new RijndaelManaged())
        {
            ICryptoTransform decryptor = rijndael.CreateDecryptor(key, iv);
            return _Decrypt(encryptedString, decryptor);
        }
    }
    public static string _Decrypt(string encryptedString, ICryptoTransform decryptor)
    {
        if (string.IsNullOrEmpty(encryptedString))
        {
            return null;
        }
        UTF8Encoding textConverter = new UTF8Encoding();
        using (MemoryStream msDecrypt = new MemoryStream())
        {

            // rijndael.Padding = PaddingMode.None;
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
            {
                byte[] encrypted = Convert.FromBase64String(encryptedString);
                csDecrypt.Write(encrypted, 0, encrypted.Length);
                csDecrypt.FlushFinalBlock();
                return textConverter.GetString(msDecrypt.ToArray());
            }
        }
    }
}

0 个答案:

没有答案