首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

.net 对数据的加密,解密有关问题

2011-12-26 
.net 对数据的加密,解密问题菜鸟提问:请问,如果我有一个密码要对他进行加密和解密,用什么方法比较好?谁给

.net 对数据的加密,解密问题
菜鸟提问:
请问,如果我有一个密码要对他进行加密和解密,用什么方法比较好?谁给给我一点代码参考。谢谢了!

[解决办法]
public static string Encrypt(string pToEncrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//把字符串放到byte数组中
//原来使用的UTF8编码,我改成Unicode编码了,不行
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
//byte[] inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt);

//建立加密对象的密钥和偏移量
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
//使得输入密码必须输入英文文本
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
//Write the byte array into the crypto stream
//(It will end up in the memory stream)
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
//Get the data back from the memory stream, and into a string
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
//Format as hex
ret.AppendFormat( "{0:X2} ", b);
}
ret.ToString();
return ret.ToString();
}

热点排行