您现在的位置是:网站首页> 编程资料编程资料
c#加密类使用方法示例_实用技巧_
2023-05-24
372人已围观
简介 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;
}
}
}
}
您可能感兴趣的文章:
相关内容
- 动态代理的5模式使用示例和Mixin模式_实用技巧_
- .NET命令行解析器示例程序(命令行选项功能)_实用技巧_
- .NET实现热插拔功能(动态替换功用)方案实例_实用技巧_
- .net让线程支持超时的方法实例和线程在执行结束后销毁的方法_实用技巧_
- ASP.NET拒绝访问临时目录的解决方法_实用技巧_
- Asp.Net Couchbase Memcached图文安装调用开发_实用技巧_
- 使用Aspose.Cells组件生成Excel文件实例_实用技巧_
- 在Web用户控件中引用样式表中样式的方法_实用技巧_
- Asp.net调试的一些问题小结_实用技巧_
- log4net创建系统日志的详细步骤_实用技巧_
