PageRenderTime 37ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/ItemConsole/RsaAuthenticationExample.cs

https://github.com/herskinduk/Usergroup.ItemWebApi
C# | 54 lines | 38 code | 6 blank | 10 comment | 0 complexity | 534fe7b0e5ccf71a1bc79a8b7f3c8886 MD5 | raw file
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace ItemConsole
  12. {
  13. public class RsaAuthenticationExample
  14. {
  15. public static void GetHomeItem()
  16. {
  17. // Aquire public key
  18. var publicKeyRequest =
  19. (HttpWebRequest)WebRequest.Create("http://usergroup/-/item/v1/-/actions/getpublickey");
  20. var publicKeyResponse = (HttpWebResponse)publicKeyRequest.GetResponse();
  21. var publicKey = new StreamReader(publicKeyResponse.GetResponseStream()).ReadToEnd();
  22. // Setup Item request
  23. var request =
  24. (HttpWebRequest)WebRequest.Create("http://usergroup/-/item/v1/sitecore/content/home");
  25. // Tell Sitecore that credentails are encrypted
  26. request.Headers.Add("X-Scitemwebapi-Encrypted", "1");
  27. // Username and password
  28. request.Headers.Add("X-Scitemwebapi-Username", RsaEncrypt("admin", publicKey));
  29. request.Headers.Add("X-Scitemwebapi-Password", RsaEncrypt("b", publicKey));
  30. var response = (HttpWebResponse)request.GetResponse();
  31. ConsoleExt.WriteJsonStream(response.GetResponseStream());
  32. }
  33. /// <summary>
  34. /// RSA Encrypts a string of data and returns the encrypted data as a Base64 string
  35. /// </summary>
  36. /// <param name="data">Clear text data to be encrypted</param>
  37. /// <param name="publicKey">RSA xml config</param>
  38. /// <returns>A Base64 encoded string representing the encrypted data</returns>
  39. private static string RsaEncrypt(string data, string publicKey)
  40. {
  41. using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
  42. {
  43. RSA.FromXmlString(publicKey);
  44. return Convert.ToBase64String(RSA.Encrypt(Encoding.UTF8.GetBytes(data), false));
  45. }
  46. }
  47. }
  48. }