• 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 = “金胖子死了”;
    

      

  • 相关阅读:
    第8章 字符串
    第7章 方法
    第6章 类和对象
    第5章 数组
    第4章 循环结构、break与continue
    第3章 选择结构
    第2章 变量、数据类型和运算符
    Codeforces Round #426 (Div. 2)
    CCNA学前基础一
    Tinkoff Challenge
  • 原文地址:https://www.cnblogs.com/cfas/p/3174747.html
Copyright © 2020-2023  润新知