.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)); } } }
最後更新:2017-04-02 04:01:44
上一篇:
Ubuntu 9.10禁用觸摸板的辦法
下一篇:
.NET中的加密類(對稱加密)
WinForm中提示Circular base class dependency involving 'TestEncryption.Form' and 'TestEncryption.Form
CDN HTTPS安全加速解決方案發布,價格下調50%
想充分利用NFV?Cloud Native是個好方法
java 中反射的應用
使用Aliplayer在微信中播放視頻的正確姿勢
訊飛語音
團隊管理中的第六人模式 .
Keeping Your Data Secure with Web Application Firewall
第1期:雲棲北歐120㎡自然優雅三居裝修案例
DOM4J解析XML