c#

位置:IT落伍者 >> c# >> 浏览文章

C# 对称算法,加密解密类


发布日期:2023年01月20日
 
C# 对称算法,加密解密类

模块编号

包含

作者

审核

编写日期

描述提供对称加密摘要算法

如果模块有修改则每次修改添加以下注释

Log编号

修改作者

修改日期

修改描述

using SystemText;

using SystemIO;

using System;

using SystemTextRegularExpressions;

using SystemSecurityCryptography;

namespace LHCHIPCommon

{

/**//// <summary>

/// 对称加密算法类

/// </summary>

public class DecryptEncrypt

{

/**//// <summary>

/// 返回自身的一个类

/// </summary>

public static DecryptEncrypt MyDecryptEncrypt

{

get

{

return new DecryptEncrypt();

}

}

private SymmetricAlgorithm mobjCryptoService;

private string Key;

/**//// <summary>

/// 对称加密类的构造函数

/// </summary>

internal DecryptEncrypt()

{

mobjCryptoService = new RijndaelManaged();

Key = rrp(%&hxH$jgsfgfsIFtma&fvHrr&&*h%(lJ$lhj!y&(*jkPera;

}

/**//// <summary>

/// 获得密钥

/// </summary>

/// <returns>密钥</returns>

private byte[] GetLegalKey()

{

string _TempKey = Key;

mobjCryptoServiceGenerateKey();

byte[] bytTemp = mobjCryptoServiceKey;

int KeyLength = bytTempLength;

if (_TempKeyLength > KeyLength)

_TempKey = _TempKeySubstring( KeyLength);

else if (_TempKeyLength < KeyLength)

_TempKey = _TempKeyPadRight(KeyLength );

return ASCIIEncodingASCIIGetBytes(_TempKey);

}

/**//// <summary>

/// 获得初始向量IV

/// </summary>

/// <returns>初试向量IV</returns>

private byte[] GetLegalIV()

{

string _TempIV = @afetj*Ghg!rNIfsgrGUqdgsrb#GGHBh(urjjHJ($jhWk&!hjjri%$hjk;

mobjCryptoServiceGenerateIV();

byte[] bytTemp = mobjCryptoServiceIV;

int IVLength = bytTempLength;

if (_TempIVLength > IVLength)

_TempIV = _TempIVSubstring( IVLength);

else if (_TempIVLength < IVLength)

_TempIV = _TempIVPadRight(IVLength );

return ASCIIEncodingASCIIGetBytes(_TempIV);

}

/**//// <summary>

/// 加密方法

/// </summary>

/// <param name=Source>待加密的串</param>

/// <returns>经过加密的串</returns>

public string Encrypto(string Source)

{

byte[] bytIn = UTFEncodingUTFGetBytes(Source);

MemoryStream ms = new MemoryStream();

mobjCryptoServiceKey = GetLegalKey();

mobjCryptoServiceIV = GetLegalIV();

//创建对称加密器对象

ICryptoTransform encrypto = mobjCryptoServiceCreateEncryptor();

//定义将数据流链接到加密转换的流

CryptoStream cs = new CryptoStream(ms encrypto CryptoStreamModeWrite);

csWrite(bytIn bytInLength);

csFlushFinalBlock();

msClose();

byte[] bytOut = msToArray();

return ConvertToBaseString(bytOut);

}

/**//// <summary>

/// 解密方法

/// </summary>

/// <param name=Source>待解密的串</param>

/// <returns>经过解密的串</returns>

public string Decrypto(string Source)

{

byte[] bytIn = ConvertFromBaseString(Source);

MemoryStream ms = new MemoryStream(bytIn bytInLength);

mobjCryptoServiceKey = GetLegalKey();

mobjCryptoServiceIV = GetLegalIV();

//创建对称解密器对象

ICryptoTransform encrypto = mobjCryptoServiceCreateDecryptor();

//定义将数据流链接到加密转换的流

CryptoStream cs = new CryptoStream(ms encrypto CryptoStreamModeRead);

StreamReader sr = new StreamReader(cs);

return srReadToEnd();

}

}

}

               

上一篇:C# webservice调用方法总结

下一篇:ado.net快速上手实践篇(二)