C#常用加密解密方法(DES加密解密)

在日常开发过程中,总会遇到需要加密解密的需求,这里我整理了C#常用的加密解密方法分享给大家。

先看看加密的基本概念:

"加密",是一种限制对网络上传输数据的访问权的技术。原始数据(也称为明文,plaintext)被加密设备(硬件或软件)和密钥加密而产生的经过编码的数据称为密文(ciphertext)。将密文还原为原始明文的过程称为解密,它是加密的反向处理,但解密者必须利用相同类型的加密设备和密钥对密文进行解密。

加密的基本功能包括:

1. 防止不速之客查看机密的数据文件;

2. 防止机密数据被泄露或篡改;

3. 防止特权用户(如系统管理员)查看私人数据文件;

4. 使入侵者不能轻易地查找一个系统的文件。

一、本节摘要 

本节主要分享DES加密解密:

        DES,全称Data Encryption Standard,是一种对称加密算法。由于其安全性比较高(有限时间内,没有一种加密方法可以说是100%安全),很可能是最广泛的密钥系统(我们公司也在用,估计你们也有在用....),唯一一种方法可以破解该算法,那就是穷举法。

DES(Data Encryption Standard)和TripleDES是对称加密的两种实现。

DES和TripleDES基本算法一致,只是TripleDES算法提供的key位数更多,加密可靠性更高。

DES使用的密钥key为8字节,初始向量IV也是8字节。

TripleDES使用24字节的key,初始向量IV也是8字节。

两种算法都是以8字节为一个块进行加密,一个数据块一个数据块的加密,一个8字节的明文加密后的密文也是8字节。如果明文长度不为8字节的整数倍,添加值为0的字节凑满8字节整数倍。所以加密后的密文长度一定为8字节的整数倍。

二、源码分享 

using System;
using System.Security.Cryptography;  
using System.Text;
namespace Core.Common
{
	/// <summary>
	/// DES加密/解密类。
	/// </summary>
	public class DESEncrypt
	{
		public DESEncrypt()
		{			
		}

		#region ========加密======== 
 
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
		public static string Encrypt(string Text) 
		{
			return Encrypt(Text,"MARCOPRO");
		}
		/// <summary> 
		/// 加密数据 
		/// </summary> 
		/// <param name="Text"></param> 
		/// <param name="sKey"></param> 
		/// <returns></returns> 
		public static string Encrypt(string Text,string sKey) 
		{ 
			DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
			byte[] inputByteArray; 
			inputByteArray=Encoding.Default.GetBytes(Text); 
			des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
			des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
			System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
			CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write); 
			cs.Write(inputByteArray,0,inputByteArray.Length); 
			cs.FlushFinalBlock(); 
			StringBuilder ret=new StringBuilder(); 
			foreach( byte b in ms.ToArray()) 
			{ 
				ret.AppendFormat("{0:X2}",b); 
			} 
			return ret.ToString(); 
		} 
		#endregion
		
		#region ========解密======== 
   
 
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
		public static string Decrypt(string Text) 
		{
            return Decrypt(Text, "MARCOPRO");
		}
		/// <summary> 
		/// 解密数据 
		/// </summary> 
		/// <param name="Text"></param> 
		/// <param name="sKey"></param> 
		/// <returns></returns> 
		public static string Decrypt(string Text,string sKey) 
		{ 
			DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
			int len; 
			len=Text.Length/2; 
			byte[] inputByteArray = new byte[len]; 
			int x,i; 
			for(x=0;x<len;x++) 
			{ 
				i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); 
				inputByteArray[x]=(byte)i; 
			} 
			des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
			des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
			System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
			CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write); 
			cs.Write(inputByteArray,0,inputByteArray.Length); 
			cs.FlushFinalBlock(); 
			return Encoding.Default.GetString(ms.ToArray()); 
		} 
		#endregion 
	}
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
以下是使用C#进行DES加密和解密的代码示例: ```csharp using System; using System.Security.Cryptography; using System.Text; public class DESExample { public static string Encrypt(string plainText, byte[] key, byte[] iv) { byte[] encrypted; using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = key; des.IV = iv; ICryptoTransform encryptor = des.CreateEncryptor(des.Key, des.IV); using (var memoryStream = new System.IO.MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { using (var streamWriter = new System.IO.StreamWriter(cryptoStream)) { streamWriter.Write(plainText); } encrypted = memoryStream.ToArray(); } } } return Convert.ToBase64String(encrypted); } public static string Decrypt(string cipherText, byte[] key, byte[] iv) { byte[] decrypted; using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = key; des.IV = iv; ICryptoTransform decryptor = des.CreateDecryptor(des.Key, des.IV); using (var memoryStream = new System.IO.MemoryStream(Convert.FromBase64String(cipherText))) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { using (var streamReader = new System.IO.StreamReader(cryptoStream)) { decrypted = Encoding.UTF8.GetBytes(streamReader.ReadToEnd()); } } } } return Encoding.UTF8.GetString(decrypted); } } ``` 使用示例: ```csharp byte[] key = Encoding.UTF8.GetBytes("01234567"); byte[] iv = Encoding.UTF8.GetBytes("abcdefgh"); string plainText = "Hello, World!"; string encryptedText = DESExample.Encrypt(plainText, key, iv); Console.WriteLine($"Encrypted: {encryptedText}"); string decryptedText = DESExample.Decrypt(encryptedText, key, iv); Console.WriteLine($"Decrypted: {decryptedText}"); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MarcoPro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值