查看:2249|回复:1
关于ASP.net C#使用RSA加密的代码示例分享发表时间:2013-01-09 18:17:44

hanhan123

0分享0主题0帖子

学徒一级

(初出茅庐)

public static string RSADecrypt(this string s, string key)
       {
           string result = null;
           if (string.IsNullOrEmpty(s)) throw new ArgumentException("An empty string value cannot be encrypted.");
           if (string.IsNullOrEmpty(key)) throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
           CspParameters cspp = new CspParameters();
           cspp.KeyContainerName = key;
           RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
           rsa.PersistKeyInCsp = true;
           string[] decryptArray = s.Split(new string[] { "-" }, StringSplitOptions.None);
           byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (a => Convert.ToByte(byte.Parse(a, System.Globalization.NumberStyles.HexNumber))));
           byte[] bytes = rsa.Decrypt(decryptByteArray, true);
           result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
           return result;
       }
       public static string RSAEncrypt(this string s, string key)
       {
           if (string.IsNullOrEmpty(s)) throw new ArgumentException("An empty string value cannot be encrypted.");
           if (string.IsNullOrEmpty(key)) throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");
           CspParameters cspp = new CspParameters();
           cspp.KeyContainerName = key;
           RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
           rsa.PersistKeyInCsp = true;
           byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(s), true);
           return BitConverter.ToString(bytes);
       }

洗心、革面。

0分享0主题0帖子

学徒一级

(初出茅庐)

有一个加密算法,采用密钥加密的。
using System.Security.Cryptography;
//加密
public static String JiaMi(String str)
{
String encryptKey = "Oyea";
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
byte[] key = Encoding.Unicode.GetBytes(encryptKey);
byte[] data = Encoding.Unicode.GetBytes(str);
System.IO.MemoryStream MStream = new System.IO.MemoryStream();
CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data, 0, data.Length);
CStream.FlushFinalBlock();
return Convert.ToBase64String(MStream.ToArray());
}
//解密
public static String JieMi(String str)
{
String encryptKey = "Oyea";
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
byte[] key = Encoding.Unicode.GetBytes(encryptKey);
byte[] data = Convert.FromBase64String(str);
System.IO.MemoryStream MStream = new System.IO.MemoryStream();
CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key,key), CryptoStreamMode.Write);
CStream.Write(data, 0, data.Length);
CStream.FlushFinalBlock();
return Encoding.Unicode.GetString(MStream.ToArray());
}

回复时间:2013-01-09 18:18:46 回复

您需要登录以后才可以回帖    登录|注册