国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

用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();
}
}
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 遵义县| 咸宁市| 济源市| 肥西县| 崇阳县| 酉阳| 深水埗区| 大埔区| 大名县| 镇沅| 汉源县| 元谋县| 东乡县| 丰都县| 黑水县| 甘泉县| 精河县| 榆中县| 班玛县| 渝北区| 湘阴县| 准格尔旗| 南康市| 韶山市| 巴塘县| 监利县| 太白县| 兖州市| 阳谷县| 宜君县| 诏安县| 平远县| 房山区| 启东市| 揭阳市| 平顺县| 巫溪县| 乌兰县| 广德县| 华蓥市| 疏附县|