zoukankan      html  css  js  c++  java
  • C# DES 加密

    代码
    /// <summary>
    /// DES加密
    /// </summary>
    /// <param name="toEncryptString">要加密的字符串</param>
    /// <param name="keyString">密钥(必须为8位)</param>
    /// <returns>以Base64格式返回的加密字符串</returns>
    public static string DESEncrypt(string toEncryptString, string keyString)
    {
        
    using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
        {
            
    byte[] toEncryptBytes = Encoding.UTF8.GetBytes(toEncryptString);
            des.Key 
    = ASCIIEncoding.ASCII.GetBytes(keyString);
            des.IV 
    = ASCIIEncoding.ASCII.GetBytes(keyString);
            System.IO.MemoryStream ms 
    = new System.IO.MemoryStream();
            
    using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(toEncryptBytes, 
    0, toEncryptBytes.Length);
                cs.FlushFinalBlock();
                cs.Close();
            }
            
    string encryptedString = Convert.ToBase64String(ms.ToArray());
            ms.Close();
            
    return encryptedString;
        }
    }

    /// <summary>
    /// DES解密
    /// </summary>
    /// <param name="toDecryptString">要解密的Base64字符串</param>
    /// <param name="keyString">密钥(必须为8位)</param>
    /// <returns>已解密的字符串</returns>
    public static string DESDecrypt(string toDecryptString, string keyString)
    {
        
    byte[] toDecryptBytes = Convert.FromBase64String(toDecryptString);
        
    using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
        {
            des.Key 
    = ASCIIEncoding.ASCII.GetBytes(keyString);
            des.IV 
    = ASCIIEncoding.ASCII.GetBytes(keyString);
            System.IO.MemoryStream ms 
    = new System.IO.MemoryStream();
            
    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(toDecryptBytes, 
    0, toDecryptBytes.Length);
                cs.FlushFinalBlock();
                cs.Close();
            }
            
    string decryptedString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            
    return decryptedString;
        }

    要引用 System.Security.Cryptography 命名空间。

  • 相关阅读:
    喜马拉雅第三方客户端开发(接口和接口数据解析)。
    jquery-easyui中datagrid扩展,隐藏显示表头功能
    backbone ,jQuery-easyui,knockoutjs的整合使用
    WPF中的瀑布流布局(TilePanel)控件
    使用this.$refs['formName'].resetFields()无法重置表单
    js获取json对象的key值
    Hash表算法详解
    Redis入门
    ASP.Net 下载大文件的实现
    后端生成二维码
  • 原文地址:https://www.cnblogs.com/anjou/p/1821799.html
Copyright © 2011-2022 走看看