如何在c#中使用加密类-创新互联
这篇文章将为大家详细讲解有关如何在c#中使用加密类,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Web;
namespace Encryption.App_Code
{
///
/// 加密码类
///
public class Encryption
{
///
/// 加密
///
///
///
public static string DesEncrypt(string inputString)
{
return DesEncrypt(inputString, Key);
}
///
/// 解密
///
///
///
public static string DesDecrypt(string inputString)
{
return DesDecrypt(inputString, Key);
}
///
/// 密匙
///
private static string Key
{
get
{
return "hongye10";
}
}
///
/// 加密字符串
/// 注意:密钥必须为8位
///
/// 字符串
/// 密钥
/// 返回加密后的字符串
public static string DesEncrypt(string inputString, string encryptKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(inputString);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception error)
{
//return error.Message;
return null;
}
}
///
/// 解密字符串
///
/// 加了密的字符串
/// 密钥
/// 返回解密后的字符串
public static string DesDecrypt(string inputString, string decryptKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] inputByteArray = new Byte[inputString.Length];
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(inputString);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetString(ms.ToArray());
}
catch (System.Exception error)
{
//return error.Message;
return null;
}
}
}
}关于如何在c#中使用加密类就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
文章名称:如何在c#中使用加密类-创新互联
标题来源:http://www.scyingshan.cn/article/dcdicc.html


咨询
建站咨询
