首页 > 开发 > 综合 > 正文

用C#实现的数据加密(一) —— 对称加密算法

2024-07-21 02:19:45
字体:
来源:转载
供稿:网友


用c#实现的数据加密(一) —— 对称加密算法



以下是关于对称加密算法的c#实现代码,大家可以根据需要更改不同的算法,文中以rijndael算法为例:

using system;
using system.io;
using system.security.cryptography;
using system.text;

namespace datacrypto
{
/// <summary>
/// 对称加密算法类
/// </summary>
public class symmetricmethod
{

private symmetricalgorithm mobjcryptoservice;
private string key;
/// <summary>
/// 对称加密类的构造函数
/// </summary>
public symmetricmethod()
{
mobjcryptoservice = new rijndaelmanaged();
key = "guz(%&hj7x89h$yubi0456ftmat5&fvhufcy76*h%(hilj$lhj!y6&(*jkp87jh7";
}
/// <summary>
/// 获得密钥
/// </summary>
/// <returns>密钥</returns>
private byte[] getlegalkey()
{
string stemp = key;
mobjcryptoservice.generatekey();
byte[] byttemp = mobjcryptoservice.key;
int keylength = byttemp.length;
if (stemp.length > keylength)
stemp = stemp.substring(0, keylength);
else if (stemp.length < keylength)
stemp = stemp.padright(keylength, ' ');
return asciiencoding.ascii.getbytes(stemp);
}
/// <summary>
/// 获得初始向量iv
/// </summary>
/// <returns>初试向量iv</returns>
private byte[] getlegaliv()
{
string stemp = "e4ghj*ghg7!rnifb&95guy86gfghub#er57hbh(u%g6hj($jhwk7&!hg4ui%$hjk";
mobjcryptoservice.generateiv();
byte[] byttemp = mobjcryptoservice.iv;
int ivlength = byttemp.length;
if (stemp.length > ivlength)
stemp = stemp.substring(0, ivlength);
else if (stemp.length < ivlength)
stemp = stemp.padright(ivlength, ' ');
return asciiencoding.ascii.getbytes(stemp);
}
/// <summary>
/// 加密方法
/// </summary>
/// <param name="source">待加密的串</param>
/// <returns>经过加密的串</returns>
public string encrypto(string source)
{
byte[] bytin = utf8encoding.utf8.getbytes(source);
memorystream ms = new memorystream();
mobjcryptoservice.key = getlegalkey();
mobjcryptoservice.iv = getlegaliv();
icryptotransform encrypto = mobjcryptoservice.createencryptor();
cryptostream cs = new cryptostream(ms, encrypto, cryptostreammode.write);
cs.write(bytin, 0, bytin.length);
cs.flushfinalblock();
ms.close();
byte[] bytout = ms.toarray();
return convert.tobase64string(bytout);
}
/// <summary>
/// 解密方法
/// </summary>
/// <param name="source">待解密的串</param>
/// <returns>经过解密的串</returns>
public string decrypto(string source)
{
byte[] bytin = convert.frombase64string(source);
memorystream ms = new memorystream(bytin, 0, bytin.length);
mobjcryptoservice.key = getlegalkey();
mobjcryptoservice.iv = getlegaliv();
icryptotransform encrypto = mobjcryptoservice.createdecryptor();
cryptostream cs = new cryptostream(ms, encrypto, cryptostreammode.read);
streamreader sr = new streamreader(cs);
return sr.readtoend();
}
}
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表