RsaUtility.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System.Security.Cryptography;
  2. using System.Security.Cryptography.X509Certificates;
  3. namespace PCC2.Security;
  4. public static class RsaUtility
  5. {
  6. public static byte[] GenerateKey(int keySize) => RSA.Create(keySize).ExportRSAPrivateKey();
  7. public static RSA FromKey(byte[] pri)
  8. {
  9. var rsa = RSA.Create();
  10. rsa.ImportRSAPrivateKey(pri, out _);
  11. return rsa;
  12. }
  13. public static X509Certificate2 GenerateShortLivedCertificate(RSA rsa, int skewSeconds)
  14. {
  15. var now = DateTimeOffset.UtcNow;
  16. return GenerateShortLivedCertificate(rsa, now.AddSeconds(-skewSeconds), now.AddSeconds(skewSeconds));
  17. }
  18. public static X509Certificate2 GenerateShortLivedCertificate(RSA rsa, DateTimeOffset? notBefore = null, DateTimeOffset? notAfter = null)
  19. {
  20. var request = new CertificateRequest(
  21. string.Empty,
  22. rsa,
  23. HashAlgorithmName.SHA512,
  24. RSASignaturePadding.Pkcs1);
  25. var now = DateTimeOffset.UtcNow;
  26. var selfSigned = request.CreateSelfSigned(notBefore ?? now.AddMinutes(0.25), notAfter ?? now.AddMinutes(0.25));
  27. //非常神奇的转换,这么一搞,能被Kestrel服务端载入并且不报“ephemeral keys”错误了,浏览器也得到了预期的证书不信任页面
  28. var pfxCertificate = new X509Certificate2(selfSigned.Export(X509ContentType.Pfx));
  29. try
  30. {
  31. pfxCertificate.FriendlyName = "ShortLiveCert";
  32. }
  33. catch
  34. {
  35. //PLATFORM SUPPORT
  36. }
  37. return pfxCertificate;
  38. }
  39. }