`
isiqi
  • 浏览: 16706686 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

.NET 2.0 Symmetric Encryption Code Sample

阅读更多

One of the most common problems when developing any web site if the need to use Symmetric Encryption to save some data in the Cookie so that it can be looped back to the user's session / identity. .NET provides a very robust mechanism in which this can be achieved and supports the most well-known of both, Symmetric and Asymmetric encryption algorithms. This MSDN article does a phenomenal job of explaining the nittie-gritties of the various algorithms available and the different scenarios in which one should use them.

Though the CryptoSampleCSSample.msi provides some samples as to how to achieve this. It fails to address one of the most common scenarios of storing the IV (the Initialization Vector) and the Key in an app.config (for Windows / Console Applications) and in web.config (for Web Applications).

This complete code demonstrates how to pickup IV and Key from the web.config / app.config and then use the values in encrypting and decrypting text values. The key thing to note is that the string needs to be converted using:

Convert.FromBase64String(IV)

NOTE: The IV and Key can be generated by using the CryptoSampleCS.exe provided in the MSDN Article mentioned above.

First, the app.config:


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

Now the full code:


using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Configuration;
    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>
        /// Initializes a new instance of the <see cref="CryptoHelper"></see> class.
        /// </summary>
        public CryptoHelper()
        {
            IV = ConfigurationManager.AppSettings["IV"];
            Key = ConfigurationManager.AppSettings["Key"];
        }

        /// <summary>
        /// Gets the encrypted value.
        /// </summary>
        /// The input value.
        /// <returns></returns>
        public string GetEncryptedValue(string inputValue)
        {
            TripleDESCryptoServiceProvider provider = this.GetCryptoProvider();
            // Create a MemoryStream.
            MemoryStream mStream = new MemoryStream();

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(mStream,
                provider.CreateEncryptor(),CryptoStreamMode.Write);

            // Convert the passed string to a byte array.: Bug fixed, see update below!
            // byte[] toEncrypt = new ASCIIEncoding().GetBytes(inputValue);
byte[] toEncrypt = new UTF8Encoding().GetBytes(inputValue);
// Write the byte array to the crypto stream and flush it. cStream.Write(toEncrypt, 0, toEncrypt.Length); cStream.FlushFinalBlock(); // Get an array of bytes from the // MemoryStream that holds the // encrypted data. byte[] ret = mStream.ToArray(); // Close the streams. cStream.Close(); mStream.Close(); // Return the encrypted buffer. return Convert.ToBase64String(ret); } /// <summary> /// Gets the crypto provider. /// </summary> /// <returns></returns> private TripleDESCryptoServiceProvider GetCryptoProvider() { TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider(); provider.IV = Convert.FromBase64String(IV); provider.Key = Convert.FromBase64String(Key); return provider; } /// <summary> /// Gets the decrypted value. /// </summary> /// The input value. /// <returns></returns> public string GetDecryptedValue(string inputValue) { TripleDESCryptoServiceProvider provider = this.GetCryptoProvider(); byte[] inputEquivalent = Convert.FromBase64String(inputValue); // Create a new MemoryStream. MemoryStream msDecrypt = new MemoryStream(); // Create a CryptoStream using the MemoryStream // and the passed key and initialization vector (IV). CryptoStream csDecrypt = new CryptoStream(msDecrypt, provider.CreateDecryptor(), CryptoStreamMode.Write); csDecrypt.Write(inputEquivalent, 0, inputEquivalent.Length); csDecrypt.FlushFinalBlock(); csDecrypt.Close(); //Convert the buffer into a string and return it. return new UTF8Encoding().GetString(msDecrypt.ToArray()); } }
Update: JT Carvalho emailed me about a bug in the code above.
"You are encoding the crypted value with AsciiEncoding and decoding it with UTF8Encoding, so in some special chars (like portuguese chars) they will not match.
I think encoding it with UTF8Encoding it will resolve this."
Thanks for pointing this out and thanks for the fix as well!


  


  
分享到:
评论

相关推荐

    Crypto Samples (C# for .NET 2.0) 加密范例.

    This library exposes security functionality to the programmer, such as random number generation, hashing, salted hashing, message authentication code, symmetric encryption, asymmetric encryption, ...

    Order‑preserving symmetric encryption.pdf

    ope算法实现过程和实例

    Dynamic Searchable Symmetric Encryption with Physical Deletion and Small Leakage

    动态可搜索对称加密(Dynamic Searchable Symmetric Encryption, DSSE)是一种允许用户对密文执行搜索操作,并能够根据要求(例如添加或删除某些密文)更新这些密文的加密技术。在云计算存储安全领域,DSSE被认为是...

    【密码学论文阅读】Efficient Searchable Symmetric Encryption for Join Queries

    内容概要:本文详细介绍了高效的可搜索对称加密协议 JXT(Join Cross-Tags),用于在加密状态下执行数据库表格的join查询。JXT协议通过对XSet和TSet数据结构的巧妙运用减少了存储膨胀,确保了快速建立及灵活更新的...

    A lightweight white-box symmetric encryption algorithm against node capture for WSNs

    A lightweight white-box symmetric encryption algorithm against node capture for WSNs

    symetric-key.rar_Symmetric-Key_encryption

    标题中的"symetric-key.rar_Symmetric-Key_encryption"暗示了我们正在讨论的是对称密钥加密技术,这是一种广泛用于数据加密的方法。对称密钥加密是加密技术的基础,它的核心特点是加密和解密使用相同的密钥。这种...

    asp.net 加密解密工具!

    1. Symmetric Encryption(对称加密):对称加密使用相同的密钥进行加密和解密,如AES(高级加密标准)、DES(数据加密标准)和Triple DES。对称加密速度快,适用于大量数据的加密,但密钥管理和分发较复杂。 2. ...

    CashScheme:对称可搜索加密,Cash的实现方案

    Cash-Highly-scalable searchable symmetric encryption with Support for Boolean Queries.pdf 重点参考:3.2章 TSet的结构如下: 实现架构 注意:这里mysql和redis都是采用了长连接的形式,这主要是因为要源源不断...

    symmetric-encryption:使用OpenSSL的Ruby项目的对称加密

    升级到SymmetricEncryption V4 对称加密的第4版在大多数要传递多个参数或以前使用哈希的API上完全采用了Ruby关键字参数。 加密和解密API现在需要任何可选参数的关键字参数。 下列情况不发生变化: encrypted = Sy

    REARGUARD Secure Keyword SearchUsing Trusted Hardware论文翻译

    《REARGUARD Secure Keyword Search Using Trusted Hardware》这篇论文探讨了一个关键的安全问题——如何在不泄露用户隐私的情况下,实现对加密数据的关键词搜索。REARGUARD是一种利用可信硬件技术来确保安全搜索的...

    asp.net中加密数据库数据

    ASP.NET提供了多种加密方法,如Symmetric Encryption(对称加密)、Asymmetric Encryption(非对称加密)和Hashing(哈希)。 1. 对称加密:在这种加密模式中,加密和解密使用相同的密钥。ASP.NET中常用的对称加密...

    c# asp.net 字符串加密解密的类

    1. **Symmetric Encryption(对称加密)**:对称加密是最常见的加密方式,因为它速度快、效率高。C#中常用的对称加密算法有AES(高级加密标准)、DES(数据加密标准)和TripleDES。例如,可以使用Aes类进行加密: `...

    symmetric-encryption-PoC

    对origin类中的内容进行encrypted ,然后将其写入encrypted类中,然后再decrypted到decrypted类中。... 您应该在Origin头下看到原始内容,在Encrypted头下看到加密内容,在Decrypted头下看到解密内容,并在控制台中...

    UDP穿越Symmetric NAT(对称型NAT)的端口猜测方法

    标题中的“UDP穿越Symmetric NAT(对称型NAT)的端口猜测方法”涉及到的是互联网通信中的一个关键问题,即如何在对称型网络地址转换(Symmetric NAT)环境中实现用户数据报协议(UDP)的数据传输。Symmetric NAT是一种...

    对称加密:使用OpenSSL的Ruby项目的对称加密

    升级到SymmetricEncryption V4 对称加密的第4版在大多数要传递多个参数或以前使用哈希的API上完全采用了Ruby关键字参数。 加密和解密API现在需要任何可选参数的关键字参数。 下列情况不发生变化: encrypted = ...

    symmetric配置文档

    Symmetric 配置文档详解 Symmetric 配置文档是一份详细的配置指南,旨在帮助初学者一步步完成 Symmetric 的安装和配置。下面我们将逐步介绍 Symmetric 配置文档中的重要知识点。 一、 配置各 group 名称以及 group...

    一种TCP协议穿透Symmetric_NAT方案

    一种TCP协议穿透Symmetric_NAT方案

    AddFlow for .NET v2.1

    Lassalle.Flow.Layout.Tree.dll和Lassalle.Flow.Layout.Symmetric.dll提供了树形布局和对称布局,前者适用于展现具有分支结构的数据,后者则在保持对称美感的同时,确保了流程图的平衡性。最后,Lassalle.Flow....

    Symmetric Number

    本题"Symmetric Number"来源于亚马逊中国的在线笔试,旨在考察应聘者的Java编程能力和问题解决技巧。对称数字是指一个数字,它的反转(从右向左读)仍然形成一个有效的数字,且与原数字相近。例如,123是131的对称...

Global site tag (gtag.js) - Google Analytics