using System; using System.IO; using System.Text; using System.Security.Cryptography; namespace APress.ProAspNet.Utility { public static class AsymmetricEncryptionUtility { //生成并保存密钥; public static string GenerateKey(string targetFile) { RSACryptoServiceProvider Algorithm = new RSACryptoServiceProvider(); //保存私钥; string CompleteKey = Algorithm.ToXmlString(true); byte[] KeyBytes = Encoding.UTF8.GetBytes(CompleteKey); KeyBytes = ProtectedData.Protect(KeyBytes, null, DataProtectionScope.LocalMachine); using (FileStream fs = new FileStream(targetFile, FileMode.Create)) { fs.Write(KeyBytes, 0, KeyBytes.Length); } //返回公钥; return Algorithm.ToXmlString(false); } //读取密钥; private static void ReadKey(RSACryptoServiceProvider algorithm, string keyFile) { byte[] KeyBytes; using(FileStream fs = new FileStream(keyFile, FileMode.Open)) { KeyBytes = new byte[fs.Length]; fs.Read(KeyBytes, 0, (int)fs.Length); } KeyBytes = ProtectedData.Unprotect(KeyBytes, null, DataProtectionScope.LocalMachine); algorithm.FromXmlString(Encoding.UTF8.GetString(KeyBytes)); } //【加密数据】 public static byte[] EncryptData(string data, string publicKey) { // 基于公钥创建加密算法; RSACryptoServiceProvider Algorithm = new RSACryptoServiceProvider(); Algorithm.FromXmlString(publicKey); // 加密当前数据; return Algorithm.Encrypt(Encoding.UTF8.GetBytes(data), true); } //【解密数据】 public static string DecryptData(byte[] data, string keyFile) { RSACryptoServiceProvider Algorithm = new RSACryptoServiceProvider(); ReadKey(Algorithm, keyFile); byte[] ClearData = Algorithm.Decrypt(data, true); return Convert.ToString(Encoding.UTF8.GetString(ClearData)); } } }
相关文章
- 12-01golang中的对称加密
- 12-01.net系统的MD5加密方法
- 12-01图像加密中测试混沌系统性能的 0-1测试/0-1 Test方法与MATLAB实现代码
- 12-01c – 生成的加密字符串在PyCrypto和Crypto中的大小不同
- 12-01浅谈--什么是非对称加密?(加密通信的原理)
- 12-01c – 在Visual Studio 2017中计算AES / CCM的时间加密
- 12-01工作中拓展的加密解密传输方式. DES对称加密传输.
- 12-01公钥password学中的素数以及对称加密
- 12-01(转)对称加密与非对称加密,以及RSA的原理
- 12-01数字签名中公钥和私钥是什么?对称加密与非对称加密,以及RSA的原理