usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Security.Cryptography;
usingSystem.IO;
namespaceComponent

{
publicclassSecurity

{
publicSecurity()

{
}
//默认密钥向量
privatestaticbyte[]Keys=
{0x12,0x34,0x56,0x78,0x90,0xAB,0xCD,0xEF};
/**////<summary>
///DES加密字符串
///</summary>
///<paramname="encryptString">待加密的字符串</param>
///<paramname="encryptKey">加密密钥,要求为8位</param>
///<returns>加密成功返回加密后的字符串,失败返回源串</returns>
publicstaticstringEncryptDES(stringencryptString,stringencryptKey)

{
try

{
byte[]rgbKey=Encoding.UTF8.GetBytes(encryptKey.Substring(0,8));
byte[]rgbIV=Keys;
byte[]inputByteArray=Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProviderdCSP=newDESCryptoServiceProvider();
MemoryStreammStream=newMemoryStream();
CryptoStreamcStream=newCryptoStream(mStream,dCSP.CreateEncryptor(rgbKey,rgbIV),CryptoStreamMode.Write);
cStream.Write(inputByteArray,0,inputByteArray.Length);
cStream.FlushFinalBlock();
returnConvert.ToBase64String(mStream.ToArray());
}
catch

{
returnencryptString;
}
}

/**////<summary>
///DES解密字符串
///</summary>
///<paramname="decryptString">待解密的字符串</param>
///<paramname="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
///<returns>解密成功返回解密后的字符串,失败返源串</returns>
publicstaticstringDecryptDES(stringdecryptString,stringdecryptKey)

{
try

{
byte[]rgbKey=Encoding.UTF8.GetBytes(decryptKey);
byte[]rgbIV=Keys;
byte[]inputByteArray=Convert.FromBase64String(decryptString);
DESCryptoServiceProviderDCSP=newDESCryptoServiceProvider();
MemoryStreammStream=newMemoryStream();
CryptoStreamcStream=newCryptoStream(mStream,DCSP.CreateDecryptor(rgbKey,rgbIV),CryptoStreamMode.Write);
cStream.Write(inputByteArray,0,inputByteArray.Length);
cStream.FlushFinalBlock();
returnEncoding.UTF8.GetString(mStream.ToArray());
}
catch

{
returndecryptString;
}
}

}
}
DES字符串加密方法 -一个实用的案例
最新推荐文章于 2024-12-24 09:01:00 发布
本文介绍了一种使用DES算法进行数据加密和解密的方法。通过实例演示了如何利用C#实现字符串的加密和解密过程,包括密钥向量的设定、加密流程及解密操作。
549

被折叠的 条评论
为什么被折叠?



