.NET中的加密类(非对称加密)

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)); } } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值