2

I have base64 string encoding/decoding functions in C# and TSQL, my problem is encoded result from C# differs from encoding result in TSQL.

My goal is:

  1. C# encoded string should be decoded in TSQL and vice-versa
  2. Both functions should have an ability to encode/decode unicode characters

C#

Convert.ToBase64String(Encoding.UTF8.GetBytes("test"));

Result: dGVzdA==

TSQL

SELECT CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("bin")))', 'NVARCHAR(MAX)')   Base64Encoding
FROM 
(
    SELECT CAST(N'test' AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp

Result: dABlAHMAdAA=

Any idea how to match the results?

0

2 Answers 2

6

SQL Server is using UTF-16. Your C# code is using UTF-8, hence the difference.

To get the C# code to use UTF-16, you can do this:

Convert.ToBase64String(Encoding.Unicode.GetBytes("test"))

Result: dABlAHMAdAA=
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for explanation, your solution worked as expected and now I have clear understanding of why it works well.
1

To get your desire result Use below TSQL

SELECT CAST('test' as varbinary(max)) FOR XML PATH(''), BINARY BASE64

2 Comments

Except 'test' is not unicode. If you change that to N'test' - you will again get the same result as in question.
@ChiragMM From the question: "My goal is: [...] Both functions should have an ability to encode/decode unicode characters," so it looks like it must be Unicode.

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.