代码改变世界

C#实现字符串加密解密类

  观海看云  阅读(317)  评论(1编辑  收藏  举报
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;


public class Encrypt
{
    
//默认密钥向量
    private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

    
/// <summary>
    
/// DES加密字符串
    
/// </summary>
    
/// <param name="encryptString">待加密的字符串</param>
    
/// <param name="encryptKey">加密密钥,要求为8位</param>
    
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
    public static string EncryptDES(string encryptString, string encryptKey)
    {
        
try
        {
            
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
            
byte[] rgbIV = Keys;
            
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider dCSP
= new DESCryptoServiceProvider();
            MemoryStream mStream
= new MemoryStream();
            CryptoStream cStream
= new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray,
0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            
return Convert.ToBase64String(mStream.ToArray());
        }
        
catch
        {
            
return encryptString;
        }
    }


    
/// <summary>
    
/// DES解密字符串
    
/// </summary>
    
/// <param name="decryptString">待解密的字符串</param>
    
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
    
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
    public static string DecryptDES(string decryptString, string decryptKey)
    {
        
try
        {
            
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
            
byte[] rgbIV = Keys;
            
byte[] inputByteArray = Convert.FromBase64String(decryptString);
            DESCryptoServiceProvider DCSP
= new DESCryptoServiceProvider();
            MemoryStream mStream
= new MemoryStream();
            CryptoStream cStream
= new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray,
0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            
return Encoding.UTF8.GetString(mStream.ToArray());
        }
        
catch
        {
            
return decryptString;
        }
    }
}
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
点击右上角即可分享
微信分享提示