• C# DES加解密


            
    加密
    public static string Encrypt(string sourceString, string key, string iv)
            {
                try
                {
                    byte[] btKey = Encoding.UTF8.GetBytes(key);
    
                    byte[] btIV = Encoding.UTF8.GetBytes(iv);
    
                    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    
                    using (MemoryStream ms = new MemoryStream())
                    {
                        byte[] inData = Encoding.UTF8.GetBytes(sourceString);
                        try
                        {
                            using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                            {
                                cs.Write(inData, 0, inData.Length);
    
                                cs.FlushFinalBlock();
                            }
    
                            return Convert.ToBase64String(ms.ToArray());
                        }
                        catch
                        {
                            return sourceString;
                        }
                    }
                }
                catch { }
    
                return "DES加密出错";
            }
    调用:
                string recordString = Encrypt("金胖子死了", "20111219", "12345678");
    结果:recordString= "xQ969nexy964SXhkTuekUQ=="
    

      解密

            public static string Decrypt(string encryptedString, string key, string iv)
            {
                byte[] btKey = Encoding.UTF8.GetBytes(key);
    
                byte[] btIV = Encoding.UTF8.GetBytes(iv);
    
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] inData = Convert.FromBase64String(encryptedString);
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);
    
                            cs.FlushFinalBlock();
                        }
    
                        return Encoding.UTF8.GetString(ms.ToArray());
                    }
                    catch
                    {
                        return encryptedString;
                    }
                }
            }
    调用:string recordString = DESOperation.Decrypt("xQ969nexy964SXhkTuekUQ==", "20111219", "12345678");
    结果:recordString = “金胖子死了”;
    

      

  • 相关阅读:
    NetCore+AutoMapper多个对象映射到一个Dto对象
    log4net快速上手
    WebService基于soapheader的身份验证
    Canvas入门笔记-实现极简画笔
    .Net修改网站项目调试时的虚拟目录
    Roslyn导致发布网站时报错:编译失败
    .NET通过字典给类赋值
    键盘测试工具
    索引器基类定义
    自定义队列任务执行器
  • 原文地址:https://www.cnblogs.com/cfas/p/3174747.html
Copyright © 2020-2023  润新知