C# 加密解密字符方法Cryptography
DESCryptoServiceProvider 是 .NET Framework 中一个用于实现数据加密标准(DES)算法的类
1。它作为加密服务提供程序(CSP)的包装对象,专门用于访问DES算法的加密服务
1。该类属于System.Security.Cryptography命名空间,位于System.Security.Cryptography.dll程序集中
2。
核心特性与工作原理
DES是一种对称加密算法,使用相同的密钥对数据进行加密和解密操作
5。在DESCryptoServiceProvider的使用过程中,开发者只需设置两个关键参数:Key(密钥)和IV(初始化向量)
1。该类的实例通过调用CreateEncryptor或CreateDecryptor方法创建加密/解密转换器,这些转换器可与CryptoStream配合实现对数据流的加密处理
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;namespace Decode_Read
{public class JiaMi{private const string KEYData = "JiaMiKey";private const string IVData = "JiaMiKey";//解密public static string Decrypt(string data){byte[] Keyarray = System.Text.ASCIIEncoding.ASCII.GetBytes(KEYData);byte[] IVarray = System.Text.ASCIIEncoding.ASCII.GetBytes(IVData);byte[] byEnc;try{byEnc = Convert.FromBase64String(data); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();MemoryStream ms = new MemoryStream(byEnc);CryptoStream cstream = new CryptoStream(ms, cryptoProvider.CreateDecryptor(Keyarray, IVarray), CryptoStreamMode.Read);StreamReader sr = new StreamReader(cstream);return sr.ReadToEnd();}catch{return null;}}//加密public static string Encryption(string data){byte[] Keyarray = System.Text.ASCIIEncoding.ASCII.GetBytes(KEYData);byte[] IVarray = System.Text.ASCIIEncoding.ASCII.GetBytes(IVData);DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();int i = cryptoProvider.KeySize;MemoryStream ms = new MemoryStream();CryptoStream cstream = new CryptoStream(ms, cryptoProvider.CreateEncryptor(Keyarray, IVarray), CryptoStreamMode.Write);StreamWriter sw = new StreamWriter(cstream);sw.Write(data);sw.Flush();cstream.FlushFinalBlock();sw.Flush();return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);}}
}