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






本文转自LoveJenny博客园博客,原文链接:http://www.cnblogs.com/LoveJenny/archive/2011/06/15/2081116.html,如需转载请自行联系原作者
目录
相关文章
|
1月前
|
数据安全/隐私保护
使用加密工具类进行有效的字符串加密——CSDN博客
使用加密工具类进行有效的字符串加密——CSDN博客
14 0
|
1月前
|
数据安全/隐私保护
常用的字符串加密解密工具类
常用的字符串加密解密工具类
13 0
|
3月前
|
C# 开发者
C# 10.0引入常量插值字符串:编译时确定性的新篇章
【1月更文挑战第22天】在C# 10.0中,微软为开发者带来了一项引人注目的新特性——常量插值字符串。这一功能允许在编译时处理和计算字符串插值表达式,从而得到可以在编译时确定的常量字符串。本文将深入探讨C# 10.0中常量插值字符串的概念、工作原理、使用场景及其对现有字符串处理方式的改进,旨在帮助读者更好地理解和应用这一强大的新特性。
|
3月前
|
编译器 C# 开发者
C# 10.0中插值字符串的改进:灵活性与性能的双重提升
【1月更文挑战第19天】C# 10.0带来了对插值字符串的显著改进,进一步增强了这一功能的灵活性和性能。插值字符串是C#中处理字符串格式化的一种强大方式,它允许开发者直接在字符串中嵌入变量和表达式。在C# 10.0中,插值字符串不仅获得了语法上的简化,还通过新的编译时优化提高了运行时性能。本文将详细探讨C# 10.0中插值字符串的改进内容,以及这些改进如何为开发者带来更加高效和便捷的编程体验。
|
5天前
|
存储 安全 网络安全
C#编程的安全性与加密技术
【4月更文挑战第21天】C#在.NET框架支持下,以其面向对象和高级特性成为安全软件开发的利器。本文探讨C#在安全加密领域的应用,包括使用System.Security.Cryptography库实现加密算法,利用SSL/TLS保障网络传输安全,进行身份验证,并强调编写安全代码的重要性。实际案例涵盖在线支付、企业应用和文件加密,展示了C#在应对安全挑战的同时,不断拓展其在该领域的潜力和未来前景。
|
1月前
|
C#
C# 字节数组与INT16,float,double之间相互转换,字符数组与字符串相互转换,
C# 字节数组与INT16,float,double之间相互转换,字符数组与字符串相互转换,
37 1
|
2月前
|
Java 数据安全/隐私保护
6-4 字符串加密(Java解法,两种网上的类型题)
6-4 字符串加密(Java解法,两种网上的类型题)
23 0
|
3月前
|
JSON C# 开发者
C# 11.0引入自然字符串字面量:简化字符串处理的新时代
【1月更文挑战第26天】C# 11.0带来了一个令人兴奋的新特性:自然字符串字面量。这一特性旨在简化字符串的创建和处理,使开发者能够更直观地编写涉及多行字符串、转义字符和插值表达式的代码。自然字符串字面量不仅提高了代码的可读性,还减少了因转义字符引起的错误。本文将深入探讨C# 11.0中自然字符串字面量的概念、使用方法和其对现有字符串处理方式的改进。
|
3月前
|
存储 C# 索引
C# 字符串操作指南:长度、连接、插值、特殊字符和实用方法
字符串用于存储文本。一个字符串变量包含由双引号括起的字符集合
65 2
|
4月前
|
C# 图形学
【Unity 3D】C#中String类的介绍及字符串常用操作详解(附测试代码 超详细)
【Unity 3D】C#中String类的介绍及字符串常用操作详解(附测试代码 超详细)
76 0