在Dapper.NET中使用varbinary參數

.net c# dapper sql-server

我正在嘗試使用Dapper.NET的varbinary參數,如下所示

string secret = "secret";

// from SELECT ENCRYPTBYPASSPHRASE('secret', N'xx') >>;
string ciphertext = "0x01000000393FE233AE939CA815AB744DDC39667860B3B630C82F36F7"; 
using (var conn = new SqlConnection(...))
{
    var result = conn.ExecuteScalar(@"SELECT CONVERT(NVARCHAR(4000), DECRYPTBYPASSPHRASE(@secret, @ciphertext)) as decrypted", 
        new
        {
            secret,
            ciphertext = Encoding.Unicode.GetBytes(ciphertext)
        });
}

但結果為null 。但是如果我直接運行SQL,它會返回一個有效的結果,例如。

SELECT CONVERT(NVARCHAR(40), DECRYPTBYPASSPHRASE('secret',  0x01000000393FE233AE939CA815AB744DDC39667860B3B630C82F36F7))

返回xx ,這是加密文本。

知道我做錯了什麼嗎?

一般承認的答案

只是有人發現有用,以下工作(感謝@Rob上面的評論)

public string Encrypt(string secret, string unprotectedText)
{
    using (var conn = new SqlConnection(...))
    {
        var x = conn.ExecuteScalar(@"SELECT ENCRYPTBYPASSPHRASE(@secret, @text)",
            new { secret, text });

        return ByteArrayToString((byte[])x);
    }
}

public string Decrypt(string secret, string ciphertext)
{
    using (var conn = new SqlConnection(...))
    {
        return conn.ExecuteScalar(@"SELECT CONVERT(NVARCHAR(4000), DECRYPTBYPASSPHRASE(@secret, @ciphertext))", 
            new { secret, ciphertext = StringToByteArray(ciphertext) }).ToString();
    }
}

以及hexstring-to-bytes和bytes-to-hexstring函數

public static byte[] StringToByteArray(string hex)
{
    int startIndex = 0;
    if (hex.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
        startIndex = 2;

    return Enumerable.Range(startIndex, hex.Length - startIndex)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

public static string ByteArrayToString(byte[] arr)
{
    return "0x" + BitConverter.ToString(arr).Replace("-", String.Empty);
}


許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow