How to update a varbinary field with a specific value?

shicky picture shicky · Dec 19, 2011 · Viewed 63.9k times · Source

Basically I am trying to give a user a certain password so I can test some functionality on a system, as I only have our admin account and I can't play with that I am just picking a random account so I can do my testing. So here is my attempt at an update:

UPDATE dbo.Login
SET
  Salt=CAST('bPftidzyAQik' AS VARBINARY),
  Password=CAST('0x2B89C2954E18E15759545A421D243E251784FA009E46F7A163926247FDB945F85F095DBB1FFF5B2B43A6ADAE27B8C46E176902412C4F8943E39528FF94E0DD5B' AS VARBINARY)
WHERE LoginID=10947

It runs fine however the code in the database looks japanese for one and the syntax for the other looks fine but its not the value i'm putting in, I want it to use the exact value I put in so I can sign in. How do I do this? I've tried several different cast and convert solutions with no luck.

Answer

Jake Feasel picture Jake Feasel · Dec 19, 2011

Try this:

UPDATE dbo.Login
SET
  Salt=CAST('bPftidzyAQik' AS VARBINARY),
  Password=0x2B89C2954E18E15759545A421D243E251784FA009E46F7A163926247FDB945F85F095DBB1FFF5B2B43A6ADAE27B8C46E176902412C4F8943E39528FF94E0DD5B
WHERE LoginID=10947

(you don't need to cast a string storing a hex value into varbinary - that's just what it is by default, without the quotes)

The question is, how are you generating that password hex value, and are you using the same encoding to generate it as you are to read it? If you are planning on converting that data back into a string, you'll need some code to do so. Here's a function I wrote that does this:

CREATE FUNCTION ConvertBinary
(  
    @value AS varbinary(max)
) RETURNS VARCHAR(MAX) AS BEGIN  

    DECLARE @result AS varbinary(max),
            @result2 AS varchar(max),
            @idx AS bigint;

    IF @value IS null
        return null;

    SELECT @result = @value;  
    SELECT @result2 = '';
    SELECT @idx = 1;

    WHILE substring(@result, @idx, 1) != 0 AND @idx < len(@result)
        BEGIN
            SET @result2 = @result2 + cast(substring(@result,@idx,1) as char(1));  
            SET @idx = @idx + 1;
        END

    RETURN @result2;  

END 

I don't know how helpful this will be for you, though, since it's very possible that whatever app is using these fields is handling the values differently than this function expects. For the record, this function takes a varbinary value which was originally utf-8 string, and returns the varchar value of that string. Good luck!