• 3DES封装类



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Security;
    using System.Security.Cryptography;
    using System.Text;
    using System.IO;
    using System.Configuration;

    /// <summary>
    /// 3DES加解密类
    /// </summary>
    public class TriDES
    {
    //密钥
    //sKey必须使用英文字符,区分大小写,且字符数量是8个,不能多也不能少,否则出错。
    private const string sKey = "CaeHuGnh";

    //矢量,矢量可以为空
    private const string sIV = "neCgHahU";

    /// <summary>
    /// 使用3DES加密字符串
    /// </summary>
    /// <param name="_ToEntryptString">需要加密的字符串</param>
    /// <returns>加密结果字符串</returns>
    public static string Encrypt(string _ToEntryptString)
    {
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    //把字符串放到byte数组中
    byte[] inputByteArray = Encoding.Default.GetBytes(_ToEntryptString);
    //建立加密对象的密钥和偏移量
    des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    des.IV = ASCIIEncoding.ASCII.GetBytes(sIV);
    MemoryStream ms = new 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);
    }
    ret.ToString();
    return ret.ToString();
    }

    /// <summary>
    /// 解密3DES加密字符串
    /// </summary>
    /// <param name="_ToDecryptString">解密字符串</param>
    /// <returns>解密结果字符串</returns>
    public static string Decrypt(string _ToDecryptString)
    {
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    //Put the input string into the byte array
    byte[] inputByteArray = new byte[_ToDecryptString.Length / 2];
    for (int x = 0; x < _ToDecryptString.Length / 2; x++)
    {
    int i = (Convert.ToInt32(_ToDecryptString.Substring(x * 2, 2), 16));
    inputByteArray[x] = (byte)i;
    }
    //建立加密对象的密钥和偏移量,此值重要,不能修改
    des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    des.IV = ASCIIEncoding.ASCII.GetBytes(sIV);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
    //Flush the data through the crypto stream into the memory stream
    cs.Write(inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock();
    //Get the decrypted data back from the memory stream
    //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
    StringBuilder ret = new StringBuilder();
    return System.Text.Encoding.Default.GetString(ms.ToArray());
    }

    }

  • 相关阅读:
    Mysql的transaction实现(转)
    开启博客模式。
    chromium获取代码和编译
    Chrome的Crash Report服务
    chromiun 学习《二》 目录结构 +启动流程
    CreateCompatibleDC与BitBlt 学习
    字符编码
    chromiun 学习《一》
    毕业后的一段日子
    学习计划
  • 原文地址:https://www.cnblogs.com/taomylife/p/3216903.html
Copyright © 2020-2023  润新知