/// <summary> /// 生成并保存 RSA 公钥与私钥 /// </summary> /// <returns></returns> private void GenerateAndSaveKey() { if (privateKey == "") { RSA.Create(); using (var rsa = new RSACryptoServiceProvider(2048)) { try { var privateKeys = rsa.ExportParameters(true); var publicKeys = rsa.ExportParameters(false); privateSK = new RsaSecurityKey(privateKeys); publicSK = new RsaSecurityKey(publicKeys); privateKey = FrameDLRObject.CreateInstance(privateKeys, FrameDLRFlags.SensitiveCase).tojsonstring(Encoding.Unicode); publicKey = FrameDLRObject.CreateInstance(publicKeys, FrameDLRFlags.SensitiveCase).tojsonstring(Encoding.Unicode); if (!string.IsNullOrEmpty(PrivateKeySavePath)) { GlobalCommon.Logger.WriteLog(LoggerLevel.INFO, $"RestAPI Token私有秘钥存放位置为{PrivateKeySavePath}"); var physicalPath = PrivateKeySavePath.Replace("~", ServerRootPath); var dirPath = Path.GetDirectoryName(physicalPath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } File.WriteAllText(physicalPath, privateKey); } if (!string.IsNullOrEmpty(PublicKeySavePath)) { GlobalCommon.Logger.WriteLog(LoggerLevel.INFO, $"RestAPI Token公有秘钥存放位置为{PublicKeySavePath}"); var physicalPath = PublicKeySavePath.Replace("~", ServerRootPath); var dirPath = Path.GetDirectoryName(physicalPath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } File.WriteAllText(physicalPath, publicKey); } } finally { rsa.PersistKeyInCsp = false; } } } }
private RsaSecurityKey GetRSAPrivateKey() { var physicalPath = PrivateKeySavePath.Replace("~", ServerRootPath); if (File.Exists(physicalPath)) { var content = File.ReadAllText(physicalPath); privateKey = content; RSAParameters rp = ((FrameDLRObject)FrameDLRObject.CreateInstance(content, FrameDLRFlags.SensitiveCase)).ToModel <RSAParameters>(Encoding.Unicode); privateSK = new RsaSecurityKey(rp); } else { GlobalCommon.Logger.WriteLog(LoggerLevel.INFO, $"Rest验证读取PrivateKey文件失败,原因是目录文件{PrivateKeySavePath}不存在,请给出正确的秘钥钥文件路径(请在验证的Logic中重载PrivateKeySavePath的get方法),没有密钥会导致token生成失败甚至出现异常"); } if (string.IsNullOrEmpty(privateKey)) { GlobalCommon.Logger.WriteLog(LoggerLevel.INFO, $"Rest创建token密钥不存在,没有密钥会导致创建失败甚至出现异常,如果本API服务提供生成Token的功能则请不要重载PublicKeySavePath和PrivateKeySavePath两个属性的get方法或在get时返回空串,如果不是则请提供正确的PrivateKeySavePath路径值"); } return(privateSK); }