Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BasicAuthentication
- {
- public const string Scheme = "Basic";
- public const char DelimiterSymbol = ':';
- public string Username { get; }
- public string Password { get; }
- private string _base64;
- public BasicAuthentication(string username, string password)
- {
- AssertNotNull(username, password);
- Username = username;
- Password = password;
- }
- public string GetBase64(Encoding encoding)
- {
- if (_base64 == null)
- {
- var bytes = encoding.GetBytes(Combine(Username, Password));
- _base64 = Convert.ToBase64String(bytes);
- }
- return _base64;
- }
- public static BasicAuthentication FromBase64(string base64, Encoding encoding)
- {
- var auth = encoding.GetString(Base64Bytes(base64))
- .Split(DelimiterSymbol);
- return new BasicAuthentication(auth[0], auth[1])
- {
- _base64 = base64
- };
- }
- public static string Combine(string username, string password)
- => $"{username}{DelimiterSymbol}{password}";
- private void AssertNotNull(string username, string password)
- {
- if (username == null)
- {
- throw new ArgumentNullException(nameof(username));
- }
- if (password == null)
- {
- throw new ArgumentNullException(nameof(password));
- }
- }
- private static byte[] Base64Bytes(string base64)
- => Convert.FromBase64String(base64);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement