Asp.net,C# 加密解密字符串的使用详解

 更新时间:2013年05月14日 11:40:20   作者:  
本篇文章对Asp.net,C# 加密解密字符串的使用进行了详细的分析介绍,需要的朋友参考下

首先在web.config | app.config 文件下增加如下代码:

复制代码 代码如下:

<?xml version="1.0"?>
  <configuration>
    <appSettings>
      <add key="IV" value="SuFjcEmp/TE="/>
      <add key="Key" value="KIPSToILGp6fl+3gXJvMsN4IajizYBBT"/>
    </appSettings>
  </configuration>

IV:加密算法的初始向量。

Key:加密算法的密钥。

接着新建类CryptoHelper,作为加密帮助类。

首先要从配置文件中得到IV 和Key。所以基本代码如下

复制代码 代码如下:

public class CryptoHelper
        {
            //private readonly string IV = "SuFjcEmp/TE=";
            private readonly string IV = string.Empty;
            //private readonly string Key = "KIPSToILGp6fl+3gXJvMsN4IajizYBBT";
            private readonly string Key = string.Empty;

            /// <summary>
            ///构造函数
            /// </summary>
            public CryptoHelper()
            {
                IV = ConfigurationManager.AppSettings["IV"];
                Key = ConfigurationManager.AppSettings["Key"];
            }
        }


注意添加System.Configuration.dll程序集引用。
在获得了IV 和Key 之后,需要获取提供加密服务的Service 类。

在这里,使用的是System.Security.Cryptography; 命名空间下的TripleDESCryptoServiceProvider类。

获取TripleDESCryptoServiceProvider 的方法如下:

复制代码 代码如下:

/// <summary>
        /// 获取加密服务类
        /// </summary>
        /// <returns></returns>
        private TripleDESCryptoServiceProvider GetCryptoProvider()
        {
            TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();

            provider.IV = Convert.FromBase64String(IV);
            provider.Key = Convert.FromBase64String(Key);

            return provider;
        }


TripleDESCryptoServiceProvider 两个有用的方法

CreateEncryptor:创建对称加密器对象ICryptoTransform.

CreateDecryptor:创建对称解密器对象ICryptoTransform

加密器对象和解密器对象可以被CryptoStream对象使用。来对流进行加密和解密。

cryptoStream 的构造函数如下:

public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode);

使用transform 对象对stream 进行转换。

完整的加密字符串代码如下:

复制代码 代码如下:

/// <summary>
        /// 获取加密后的字符串
        /// </summary>
        /// <param name="inputValue">输入值.</param>
        /// <returns></returns>
        public string GetEncryptedValue(string inputValue)
        {
            TripleDESCryptoServiceProvider provider = this.GetCryptoProvider();

            // 创建内存流来保存加密后的流
            MemoryStream mStream = new MemoryStream();

            // 创建加密转换流
            CryptoStream cStream = new CryptoStream(mStream,
            provider.CreateEncryptor(), CryptoStreamMode.Write);

            // 使用UTF8编码获取输入字符串的字节。
            byte[] toEncrypt = new UTF8Encoding().GetBytes(inputValue);

            // 将字节写到转换流里面去。
            cStream.Write(toEncrypt, 0, toEncrypt.Length);
            cStream.FlushFinalBlock();

            // 在调用转换流的FlushFinalBlock方法后,内部就会进行转换了,此时mStream就是加密后的流了。
            byte[] ret = mStream.ToArray();

            // Close the streams.
            cStream.Close();
            mStream.Close();

            //将加密后的字节进行64编码。
            return Convert.ToBase64String(ret);
        }


解密方法也类似:
复制代码 代码如下:

/// <summary>
        /// 获取解密后的值
        /// </summary>
        /// <param name="inputValue">经过加密后的字符串.</param>
        /// <returns></returns>
        public string GetDecryptedValue(string inputValue)
        {
            TripleDESCryptoServiceProvider provider = this.GetCryptoProvider();

            byte[] inputEquivalent = Convert.FromBase64String(inputValue);

            // 创建内存流保存解密后的数据
            MemoryStream msDecrypt = new MemoryStream();

            // 创建转换流。
            CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                                                        provider.CreateDecryptor(),
                                                        CryptoStreamMode.Write);

            csDecrypt.Write(inputEquivalent, 0, inputEquivalent.Length);

            csDecrypt.FlushFinalBlock();
            csDecrypt.Close();

            //获取字符串。
            return new UTF8Encoding().GetString(msDecrypt.ToArray());
        }


完整的CryptoHelper代码如下:
复制代码 代码如下:

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

namespace WindowsFormsApplication1
{
    public class CryptoHelper
    {
        //private readonly string IV = "SuFjcEmp/TE=";
        private readonly string IV = string.Empty;
        //private readonly string Key = "KIPSToILGp6fl+3gXJvMsN4IajizYBBT";
        private readonly string Key = string.Empty;

        public CryptoHelper()
        {
            IV = ConfigurationManager.AppSettings["IV"];
            Key = ConfigurationManager.AppSettings["Key"];
        }

        /// <summary>
        /// 获取加密后的字符串
        /// </summary>
        /// <param name="inputValue">输入值.</param>
        /// <returns></returns>
        public string GetEncryptedValue(string inputValue)
        {
            TripleDESCryptoServiceProvider provider = this.GetCryptoProvider();

            // 创建内存流来保存加密后的流
            MemoryStream mStream = new MemoryStream();

            // 创建加密转换流
            CryptoStream cStream = new CryptoStream(mStream,

            provider.CreateEncryptor(), CryptoStreamMode.Write);
            // 使用UTF8编码获取输入字符串的字节。
            byte[] toEncrypt = new UTF8Encoding().GetBytes(inputValue);

            // 将字节写到转换流里面去。
            cStream.Write(toEncrypt, 0, toEncrypt.Length);
            cStream.FlushFinalBlock();

            // 在调用转换流的FlushFinalBlock方法后,内部就会进行转换了,此时mStream就是加密后的流了。
            byte[] ret = mStream.ToArray();

            // Close the streams.
            cStream.Close();
            mStream.Close();

            //将加密后的字节进行64编码。
            return Convert.ToBase64String(ret);
        }

        /// <summary>
        /// 获取加密服务类
        /// </summary>
        /// <returns></returns>
        private TripleDESCryptoServiceProvider GetCryptoProvider()
        {
            TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();

            provider.IV = Convert.FromBase64String(IV);
            provider.Key = Convert.FromBase64String(Key);

            return provider;

        }

        /// <summary>
        /// 获取解密后的值
        /// </summary>
        /// <param name="inputValue">经过加密后的字符串.</param>
        /// <returns></returns>
        public string GetDecryptedValue(string inputValue)
        {
            TripleDESCryptoServiceProvider provider = this.GetCryptoProvider();
            byte[] inputEquivalent = Convert.FromBase64String(inputValue);

            // 创建内存流保存解密后的数据
            MemoryStream msDecrypt = new MemoryStream();

            // 创建转换流。
            CryptoStream csDecrypt = new CryptoStream(msDecrypt,
            provider.CreateDecryptor(),
            CryptoStreamMode.Write);

            csDecrypt.Write(inputEquivalent, 0, inputEquivalent.Length);
            csDecrypt.FlushFinalBlock();

            csDecrypt.Close();

            //获取字符串。
            return new UTF8Encoding().GetString(msDecrypt.ToArray());
        }
    }
}


使用例子:

image

相关文章

  • asp.net 退出登陆(解决退出后点击浏览器后退问题仍然可回到页面问题)

    asp.net 退出登陆(解决退出后点击浏览器后退问题仍然可回到页面问题)

    退出登陆是再常见不过的了,先清除Session,再转到登陆页面
    2009-04-04
  • Asp.net response对象与request对象使用介绍

    Asp.net response对象与request对象使用介绍

    这篇文章主要介绍了Asp.net response对象与request对象使用,需要的朋友可以参考下
    2014-04-04
  • .NET实现ChatGPT的Stream传输的过程

    .NET实现ChatGPT的Stream传输的过程

    这篇文章主要介绍了.NET如何实现ChatGPT的Stream传输,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-07-07
  • dhtmlxGrid 添加行号详细步骤

    dhtmlxGrid 添加行号详细步骤

    接下来将介绍dhtmlxGrid 添加行号首先设置属性(设置gridView属性:gridView1 .IndicatorWidth=30)/再添加事件等等感兴趣的你可以参考下
    2013-03-03
  • asp.net发送邮件实现方法

    asp.net发送邮件实现方法

    这篇文章主要介绍了asp.net发送邮件实现方法,以一个具体实例的形式详细讲述了asp.net发送邮件的技巧,需要的朋友可以参考下
    2014-10-10
  • C#将DataTable转化为List<T>

    C#将DataTable转化为List<T>

    本文给大家讲解的是如何使用C#将DataTable数据源转化为List<T>泛型集合(已知T类型) 的方法和示例,有需要的小伙伴可以参考下
    2015-06-06
  • WPF下YUV播放的D3D解决方案

    WPF下YUV播放的D3D解决方案

    这篇文章主要介绍了WPF下YUV播放的D3D解决方案,需要的朋友可以参考下
    2017-04-04
  • asp.net core项目中如何使用html文件

    asp.net core项目中如何使用html文件

    这篇文章主要给大家介绍了关于asp.net core项目中如何使用html文件的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面是随着小编来一起学习学习吧。
    2018-02-02
  • ASP.NET实现图形验证码功能

    ASP.NET实现图形验证码功能

    ASP.NET 实现图形验证码能够增强网站安全性,防止机器人攻击,本文介绍了如何使用 C# 和 ASP.NET 创建一个简单而有效的图形验证码系统,包括生成随机验证码、绘制验证码图像以及将图像输出到客户端等步骤,感兴趣的朋友一起看看吧
    2024-03-03
  • linq中的转换操作符

    linq中的转换操作符

    这篇文章介绍了linq中的转换操作符,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03

最新评论