Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. public class BasicAuthentication
  2. {
  3. public const string Scheme = "Basic";
  4.  
  5. public const char DelimiterSymbol = ':';
  6.  
  7. public string Username { get; }
  8.  
  9. public string Password { get; }
  10.  
  11. private string _base64;
  12.  
  13. public BasicAuthentication(string username, string password)
  14. {
  15. AssertNotNull(username, password);
  16.  
  17. Username = username;
  18. Password = password;
  19. }
  20.  
  21.  
  22. public string GetBase64(Encoding encoding)
  23. {
  24. if (_base64 == null)
  25. {
  26. var bytes = encoding.GetBytes(Combine(Username, Password));
  27. _base64 = Convert.ToBase64String(bytes);
  28. }
  29.  
  30. return _base64;
  31. }
  32.  
  33. public static BasicAuthentication FromBase64(string base64, Encoding encoding)
  34. {
  35. var auth = encoding.GetString(Base64Bytes(base64))
  36. .Split(DelimiterSymbol);
  37.  
  38. return new BasicAuthentication(auth[0], auth[1])
  39. {
  40. _base64 = base64
  41. };
  42. }
  43.  
  44. public static string Combine(string username, string password)
  45. => $"{username}{DelimiterSymbol}{password}";
  46.  
  47. private void AssertNotNull(string username, string password)
  48. {
  49. if (username == null)
  50. {
  51. throw new ArgumentNullException(nameof(username));
  52. }
  53. if (password == null)
  54. {
  55. throw new ArgumentNullException(nameof(password));
  56. }
  57. }
  58.  
  59. private static byte[] Base64Bytes(string base64)
  60. => Convert.FromBase64String(base64);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement