C#字符串加密解密方法实例
本文实例讲述了c#字符串加密解密方法。分享给大家供大家参考。具体如下:
static string encryptkey= "oyea";
#region 加密字符串 public static string encrypt(string str)
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="str">要加密的字符串</param>
/// <returns>返回加密后的字符串</returns>
public static string encrypt(string str)
{
descryptoserviceprovider descsp = new descryptoserviceprovider(); //实例化加/解密类对象
byte[] key = encoding.unicode.getbytes(encryptkey); //定义字节数组,用来存储密钥
byte[] data = encoding.unicode.getbytes(str);//定义字节数组,用来存储要加密的字符串
memorystream mstream = new 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());//返回加密后的字符串
}
#endregion
#region 解密字符串 public static string decrypt(string str)
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="str">要解密的字符串</param>
/// <returns>返回解密后的字符串</returns>
public static string decrypt(string str)
{
descryptoserviceprovider descsp = new descryptoserviceprovider(); //实例化加/解密类对象
byte[] key = encoding.unicode.getbytes(encryptkey); //定义字节数组,用来存储密钥
byte[] data = convert.frombase64string(str);//定义字节数组,用来存储要解密的字符串
memorystream mstream = new 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()); //返回解密后的字符串
}
#endregion
#endregion
希望本文所述对大家的c#程序设计有所帮助。