TextEncodings.Base64Url.Decode vs Convert.FromBase64String

后端 未结 1 380
南旧
南旧 2021-01-18 22:10

I was working on creating a method that would generate a JWT token. Part of the method reads a value from my web.config that services as the \"secret\" used to generate the

1条回答
  •  -上瘾入骨i
    2021-01-18 22:44

    I came across the same thing when I migrated our authentication service to .NET Core. I had a look at the source code for the libraries we used in our previous implementation, and the difference is actually in the name itself.

    The TextEncodings class has two types of text encoders, Base64TextEncoder and Base64UrlEncoder. The latter one modifies the string slightly so the base64 string can be used in an url.

    My understanding is that it is quite common to replace + and / with - and _. As a matter of fact we have been doing the same with our handshake tokens. Additionally the padding character(s) at the end can also be removed. This leaves us with the following implementation (this is from the source code):

    public class Base64UrlTextEncoder : ITextEncoder
    {
        public string Encode(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
    
            return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
        }
    
        public byte[] Decode(string text)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
    
            return Convert.FromBase64String(Pad(text.Replace('-', '+').Replace('_', '/')));
        }
    
        private static string Pad(string text)
        {
            var padding = 3 - ((text.Length + 3) % 4);
            if (padding == 0)
            {
                return text;
            }
            return text + new string('=', padding);
        }
    }
    

    0 讨论(0)
提交回复
热议问题