You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

163 lines
5.6 KiB

  1. using Common.Models.DigitalSignature;
  2. using JsonWebToken;
  3. using Microsoft.Extensions.Logging;
  4. using SignatureAPI.Controllers;
  5. using System;
  6. using System.Configuration;
  7. using System.IO;
  8. namespace SignatureAPI
  9. {
  10. public class Utlis
  11. {
  12. private readonly ILogger<BracController> _logger;
  13. private string publicKeyLocation {get;set;}
  14. private string privateKeyLocation { get; set; }
  15. public Utlis()
  16. {
  17. privateKeyLocation = Path.Combine(Directory.GetCurrentDirectory(), "keys\\Brac", "Jme_private_uat.pem");
  18. publicKeyLocation = Path.Combine(Directory.GetCurrentDirectory(), "Keys\\Brac", "BBL_public.pem");
  19. }
  20. public Utlis(ILogger<BracController> logger)
  21. {
  22. _logger = logger;
  23. privateKeyLocation = Path.Combine(Directory.GetCurrentDirectory(), "keys\\Brac", "Jme_private_uat.pem");
  24. publicKeyLocation = Path.Combine(Directory.GetCurrentDirectory(), "Keys\\Brac", "BBL_public.pem");
  25. }
  26. //public static string MapPath(string path)
  27. //{
  28. // return Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
  29. // path);
  30. //}
  31. public static string ReadWebConfig(string key, string defVal)
  32. {
  33. try
  34. {
  35. return ConfigurationManager.AppSettings[key].ToString() == null ? defVal : ConfigurationManager.AppSettings[key].ToString();
  36. }
  37. catch
  38. {
  39. return defVal;
  40. }
  41. }
  42. public JwtResponse CreateToken(string payload)
  43. {
  44. JwtResponse jwtResponse = new JwtResponse();
  45. _logger.LogInformation(payload);
  46. try
  47. {
  48. // RSA key for signing
  49. string pem = File.ReadAllText(privateKeyLocation);
  50. var signatureKey = Jwk.FromPem(pem);
  51. // RSA key for encryption
  52. pem = File.ReadAllText(publicKeyLocation);
  53. var encryptionKey = Jwk.FromPem(pem);
  54. string issuer = "jme";
  55. string subject = "api";
  56. var now = DateTime.Now;
  57. var unixTimeSeconds = new DateTimeOffset(now).ToUnixTimeSeconds();
  58. var jws = new JwsDescriptor()
  59. {
  60. SigningKey = signatureKey,
  61. Algorithm = SignatureAlgorithm.RsaSha256,
  62. ExpirationTime = now.AddMinutes(1440),
  63. IssuedAt = now,
  64. Issuer = issuer,
  65. NotBefore = DateTime.Now,
  66. Subject = subject,
  67. Payload = new JwtObject()
  68. };
  69. jws.Payload.Add("Payload", payload);
  70. jws.AddClaim("iss", issuer);
  71. // Creates a JWE descriptor with all its properties
  72. var descriptor = new JweDescriptor<JwsDescriptor>()
  73. {
  74. EncryptionKey = encryptionKey,
  75. EncryptionAlgorithm = EncryptionAlgorithm.Aes256CbcHmacSha512,
  76. Algorithm = KeyManagementAlgorithm.RsaOaep256,
  77. Payload = jws
  78. };
  79. // Generates the UTF-8 string representation of the JWT
  80. var writer = new JwtWriter();
  81. var token = writer.WriteTokenString(descriptor);
  82. jwtResponse.Id = token;
  83. jwtResponse.Extra = unixTimeSeconds.ToString();
  84. jwtResponse.ResponseCode = "0";
  85. return jwtResponse;
  86. }
  87. catch (Exception ex)
  88. {
  89. _logger.LogError(ex.ToString());
  90. jwtResponse.ResponseCode = "1";
  91. jwtResponse.Msg = ex.ToString();
  92. return jwtResponse;
  93. }
  94. }
  95. public JwtResponse ExtractPayloadFromToken(string token)
  96. {
  97. JwtResponse jwtResponse = new JwtResponse();
  98. _logger.LogInformation(token);
  99. // string jwtResponse = string.Empty;
  100. try
  101. {
  102. // RSA key for verification
  103. string pem = File.ReadAllText(publicKeyLocation);
  104. var signatureKey = Jwk.FromPem(pem);
  105. // RSA key for decryption
  106. pem = File.ReadAllText(privateKeyLocation);
  107. var decryptionKey = Jwk.FromPem(pem);
  108. string issuer = "jme";
  109. var policy = new TokenValidationPolicyBuilder()
  110. .RequireSignature(signatureKey, SignatureAlgorithm.RsaSha256)
  111. .Build();
  112. var reader = new JwtReader(decryptionKey);
  113. var result = reader.TryReadToken(token, policy);
  114. if (result.Succedeed)
  115. {
  116. JwtProperty jwtProp = new JwtProperty();
  117. var hasPayload = result.Token?.Payload?.TryGetValue("Payload", out jwtProp);
  118. if (hasPayload != null && hasPayload.Value)
  119. {
  120. jwtResponse.Data = jwtProp.Value;
  121. jwtResponse.Extra = token;
  122. jwtResponse.ResponseCode = "0";
  123. }
  124. }
  125. return jwtResponse;
  126. }
  127. catch (Exception ex)
  128. {
  129. // write exception logs to database
  130. _logger.LogError(ex.ToString());
  131. jwtResponse.ResponseCode = "1";
  132. jwtResponse.Msg = ex.ToString();
  133. return jwtResponse;
  134. }
  135. }
  136. }
  137. }