1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- using System.Security.Cryptography;
- using System.Security.Cryptography.X509Certificates;
- namespace PCC2.Security;
- public static class RsaUtility
- {
- public static byte[] GenerateKey(int keySize) => RSA.Create(keySize).ExportRSAPrivateKey();
- public static RSA FromKey(byte[] pri)
- {
- var rsa = RSA.Create();
- rsa.ImportRSAPrivateKey(pri, out _);
- return rsa;
- }
- public static X509Certificate2 GenerateShortLivedCertificate(RSA rsa, int skewSeconds)
- {
- var now = DateTimeOffset.UtcNow;
- return GenerateShortLivedCertificate(rsa, now.AddSeconds(-skewSeconds), now.AddSeconds(skewSeconds));
- }
- public static X509Certificate2 GenerateShortLivedCertificate(RSA rsa, DateTimeOffset? notBefore = null, DateTimeOffset? notAfter = null)
- {
- var request = new CertificateRequest(
- string.Empty,
- rsa,
- HashAlgorithmName.SHA512,
- RSASignaturePadding.Pkcs1);
- var now = DateTimeOffset.UtcNow;
- var selfSigned = request.CreateSelfSigned(notBefore ?? now.AddMinutes(0.25), notAfter ?? now.AddMinutes(0.25));
- //非常神奇的转换,这么一搞,能被Kestrel服务端载入并且不报“ephemeral keys”错误了,浏览器也得到了预期的证书不信任页面
- var pfxCertificate = new X509Certificate2(selfSigned.Export(X509ContentType.Pfx));
- try
- {
- pfxCertificate.FriendlyName = "ShortLiveCert";
- }
- catch
- {
- //PLATFORM SUPPORT
- }
- return pfxCertificate;
- }
- }
|