zoukankan      html  css  js  c++  java
  • 字符串的加解密

    为了方便对于字符串的加解密,.NET提供了一些内置支持。一般我们更愿意把它们封装成一个通用类,以重复使用.下面是一个范例

    public class Encrypter

    {

    private SymmetricAlgorithm mCSP;

    private const string CIV = "kXwL7X2+fgM=";

    private const string CKEY = "FwGQWRRgKCI=";

    public Encrypt()

    {

    mCSP = new DESCryptoServiceProvider();

    }

    ///对称加密

    public string EncryptString(string Value)

    {

    ICryptoTransform ct;

    MemoryStream ms;

    CryptoStream cs;

    byte[] byt;

    ct = mCSP.CreateEncryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));

    byt = Encoding.UTF8.GetBytes(Value);

    ms = new MemoryStream();

    cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);

    cs.Write(byt, 0, byt.Length);

    cs.FlushFinalBlock();

    cs.Close();

    return Convert.ToBase64String(ms.ToArray());

    }

    ///对称解密

    public string DecryptString(string Value)

    {

    ICryptoTransform ct;

    MemoryStream ms;

    CryptoStream cs;

    byte[] byt;

    ct = mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));

    byt = Convert.FromBase64String(Value);

    ms = new MemoryStream();

    cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);

    cs.Write(byt, 0, byt.Length);

    cs.FlushFinalBlock();

    cs.Close();

    return Encoding.UTF8.GetString(ms.ToArray());

    }

    ///产生哈希散列值

    public string Hashed(string input)

    {

    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

    byte[] byt = Encoding.UTF8.GetBytes(input);

    return Convert.ToBase64String(md5.ComputeHash(byt));

    }

    ///比较哈希值(注意,哈希算法是不可逆的,所以只能进行比较

    public bool CompareHash(string input, string hashedstring) {

    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

    return hashedstring.Equals(Hashed(input));

    }

    }

     

    客户程序调用的例子

    public static void Main()

    {

    Encrypter encrypt = new Encrypter();

    Console.WriteLine(encrypt.EncryptString("Hello,world"));

    Console.WriteLine(encrypt.DecryptString("sHwFBA84ozrLqSMYRrAKIw=="));

    Console.WriteLine(encrypt.Hashed("chenxizhang"));

    Console.WriteLine(encrypt.CompareHash("chenxizhang", "xLl6tY7Js1JpbssgopzBhg=="));

    Console.Read();

    }

  • 相关阅读:
    2019 年 GrapeCity Documents 产品路线图
    2019 年 Spread.NET 产品路线图(Roadmap)
    ActiveReports报表控件 V13 正式发布,提供在线报表设计和自适应报表布局
    ActiveReports 大数据分析报告:2018中国电影再次迎来黄金时代
    【Visual Studio 扩展工具】如何在ComponentOne的DataTree中实现RightToLeft布局
    JavaScript-页面打印正方形,各种三角形与菱形
    HTML入门与基础 —— 标签《一》
    springmvc异常处理
    springmvc-数据回显
    springmvc-validation校验
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1201804.html
Copyright © 2011-2022 走看看