网络安全

位置:IT落伍者 >> 网络安全 >> 浏览文章

字符串加密解密类


发布日期:2023年06月09日
 
字符串加密解密类

using System;

using SystemText;

using SystemSecurityCryptography;

using SystemIO;

//默认密钥向量

private static byte[] Keys = { x x x x x xAB xCD xEF };

/// <summary>

/// DES加密字符串

/// </summary>

/// <param name=encryptString>待加密的字符串</param>

/// <param name=encryptKey>加密密钥要求为位</param>

/// <returns>加密成功返回加密后的字符串失败返回源串</returns>

public static string EncryptDES(string encryptString string encryptKey)

{

try

{

byte[] rgbKey = EncodingUTFGetBytes(encryptKeySubstring( ));

byte[] rgbIV = Keys;

byte[] inputByteArray = EncodingUTFGetBytes(encryptString);

DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();

MemoryStream mStream = new MemoryStream();

CryptoStream cStream = new CryptoStream(mStream dCSPCreateEncryptor(rgbKey rgbIV) CryptoStreamModeWrite);

cStreamWrite(inputByteArray inputByteArrayLength);

cStreamFlushFinalBlock();

return ConvertToBaseString(mStreamToArray());

}

catch

{

return encryptString;

}

}

/// <summary>

/// DES解密字符串

/// </summary>

/// <param name=decryptString>待解密的字符串</param>

/// <param name=decryptKey>解密密钥要求为和加密密钥相同</param>

/// <returns>解密成功返回解密后的字符串失败返源串</returns>

public static string DecryptDES(string decryptString string decryptKey)

{

try

{

byte[] rgbKey = EncodingUTFGetBytes(decryptKey);

byte[] rgbIV = Keys;

byte[] inputByteArray = ConvertFromBaseString(decryptString);

DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();

MemoryStream mStream = new MemoryStream();

CryptoStream cStream = new CryptoStream(mStream DCSPCreateDecryptor(rgbKey rgbIV) CryptoStreamModeWrite);

cStreamWrite(inputByteArray inputByteArrayLength);

cStreamFlushFinalBlock();

return EncodingUTFGetString(mStreamToArray());

}

catch

{

return decryptString;

}

}

使用方法为

//获取页面字符串

var strSource = RequestForms[xxx]value;

//加密

var strResult = EncryptDES(strSource);

//解密

var strRevert = DecryptDES(strResult );

               

上一篇:使用DES对称加密代码,支持中文

下一篇:ASP.NET 2.0中保证应用程序的安全