Asp.net,C# 加密解密字串的使用詳解_實用技巧

來源:互聯網
上載者:User

首先在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 之後,需要擷取提供Data Encryption Service的Service 類。

在這裡,使用的是System.Security.Cryptography; 命名空間下的TripleDESCryptoServiceProvider類。

擷取TripleDESCryptoServiceProvider 的方法如下:

複製代碼 代碼如下:

/// <summary>
        /// 擷取Data Encryption Service類
        /// </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>
        /// 擷取Data Encryption Service類
        /// </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());
        }
    }
}


使用例子:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.