3

I'm trying to use a varbinary parameter with Dapper.NET as follows

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)
        });
}

However the result is null. But it returns a valid result if I run the SQL directly eg.

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

returns xx which is the encrypted text.

Any idea what I'm doing wrong?

2
  • 1
    Encoding.Unicode.GetBytes is going to get you the byte array of the string representation of your hex value Commented Oct 4, 2016 at 3:53
  • 1
    Use this to get the correct value for ciphertext Commented Oct 4, 2016 at 3:55

1 Answer 1

2

Just so someone finds useful, the following worked (Thanks @Rob for comments above)

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();
    }
}

and the hexstring-to-bytes and bytes-to-hexstring functions are

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.