/******************************************************************************* * Copyright © 2017-2020 Znyc.Cloudcar.Admin.Framework 版权所有 * Author: Znyc * Description: Znyc快速开发平台 * Website:http://www.Znyc.Cloudcar.Admin.com *********************************************************************************/ using Newtonsoft.Json; using System.IO; using System.Security.Cryptography; namespace Znyc.Cloudcar.Admin.Commons.Encrypt { /// /// RSA加解密工具 /// public static class RSAUtils { /// /// 从本地文件中读取用来签发Token的 RSA Key。 /// /// 存放密钥的文件夹路径 /// /// /// public static bool TryGetKeyParameters(string filePath, bool withPrivate, out RSAParameters keyParameters) { string filename = withPrivate ? "key.json" : "key.public.json"; keyParameters = default; if (Directory.Exists(filePath) == false) { return false; } keyParameters = JsonConvert.DeserializeObject(File.ReadAllText(Path.Combine(filePath, filename))); return true; } /// /// 生成并保存 RSA 公钥与私钥。 /// /// 存放密钥的文件夹路径 /// public static RSAParameters GenerateAndSaveKey(string filePath) { RSAParameters publicKeys, privateKeys; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048)) { try { privateKeys = rsa.ExportParameters(true); publicKeys = rsa.ExportParameters(false); } finally { rsa.PersistKeyInCsp = false; } } File.WriteAllText(Path.Combine(filePath, "key.json"), JsonConvert.SerializeObject(privateKeys)); File.WriteAllText(Path.Combine(filePath, "key.public.json"), JsonConvert.SerializeObject(publicKeys)); return privateKeys; } } }