温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Asp.net中对字符串进行加密解密操作

发布时间:2021-03-01 16:27:51 来源:亿速云 阅读:142 作者:戴恩恩 栏目:开发技术

本文章向大家介绍怎么在Asp.net中对字符串进行加密解密操作,主要包括怎么在Asp.net中对字符串进行加密解密操作的使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

ASP.NET 是什么

ASP.NET 是开源,跨平台,高性能,轻量级的 Web 应用构建框架,常用于通过 HTML、CSS、JavaScript 以及服务器脚本来构建网页和网站。

首先在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());
        }
    }
}

到此这篇关于怎么在Asp.net中对字符串进行加密解密操作的文章就介绍到这了,更多相关的内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI