如何在ASP.NET中传递加密的查询字符串

7

我需要在asp.net页面之间传递值。如何加密URL中的这些值? 示例:Response.Redirect("customerAdd.aspx?customerId=" + custId);

8个回答

15

请查看Mads Kristensen的文章,了解一个HttpModule,它可以加密/解密您所有的查询字符串。

http://madskristensen.net/post/httpmodule-for-query-string-encryption

他的代码使用一个HttpModule来解析传出的HTML,以加密和替换所有相对路径查询字符串。该HttpModule还捕获传入请求并重写请求URL以使用未加密的查询字符串。

好处是您可以插入该模块,您的代码不需要知道查询字符串何时加密或未加密。从代码角度看,查询字符串的工作方式与往常一样。

我们现在已经使用它超过五年了,它运行得非常好。


11
@AlexAngas,与其给我点踩,不如利用这段时间去研究一下网址被移动到哪里,并编辑我的帖子以反映这一点。我发布了这篇文章将近5年了,但我已经更新了网址。 - slolife
4
或者,通过编写一个将留存的答案来节省您的时间和社区的时间。http://meta.stackexchange.com/a/7658/6651。不好意思,没有冒犯之意。 - Alex Angas
不知道为什么,但当我从本地主机(即直接从项目运行)运行它时,它可以很好地加密。但是当我将其上传到服务器并从网站运行时,它不会加密任何内容。我错过了什么吗? - Himanshu
@slolife - 但是它会显示原始查询字符串和所有参数1或2秒钟,然后才反映出加密的URL。不是这样吗?因为我正在面临这个问题。 - prog1011
这个解决方案的输出看起来像是查询字符串被加密了,但实际上并没有。如果使用 Chrome 浏览器,您可以在网络选项卡中看到它将使用可见数据的查询字符串发出请求,然后重定向到加密的 URL。因此,这个解决方案并没有真正解决实际问题。 - Mahajan344
显示剩余2条评论

3

生成全加密文件的代码非常冗长,但可以为您完成:

建议使用SessionID作为盐值,因为它对于每个用户来说都是变化的,但在回发过程中保持稳定。

///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Symmetric key encryption and decryption using Rijndael algorithm.
// 
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// 
// Copyright (C) 2002 Obviex(TM). All rights reserved.
// 
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
namespace TDX.Portal.Utilities
{
    /// <summary>
    /// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and 
    /// decrypt data. As long as encryption and decryption routines use the same
    /// parameters to generate the keys, the keys are guaranteed to be the same.
    /// The class uses static functions with duplicate code to make it easier to
    /// demonstrate encryption and decryption logic. In a real-life application, 
    /// this may not be the most efficient way of handling encryption, so - as
    /// soon as you feel comfortable with it - you may want to redesign this class.
    /// </summary>
    public class RijndaelSimple
    {
        /// <summary>
        /// Encrypts specified plaintext using Rijndael symmetric key algorithm
        /// and returns a base64-encoded result.
        /// </summary>
        /// <param name="plainText">
        /// Plaintext value to be encrypted.
        /// </param>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be 
        /// exactly 16 ASCII characters long.
        /// </param>
        /// <param name="keySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. 
        /// Longer keys are more secure than shorter keys.
        /// </param>
        /// <returns>
        /// Encrypted value formatted as a base64-encoded string.
        /// </returns>
        public static string Encrypt(string plainText,
                                     string passPhrase,
                                     string saltValue,
                                     string hashAlgorithm,
                                     int passwordIterations,
                                     string initVector,
                                     int keySize)
        {
            // Convert strings into byte arrays.
            // Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8 
            // encoding.
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // First, we must create a password, from which the key will be derived.
            // This password will be generated from the specified passphrase and 
            // salt value. The password will be created using the specified hash 
            // algorithm. Password creation can be done in several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                            passPhrase,
                                                            saltValueBytes,
                                                            hashAlgorithm,
                                                            passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate encryptor from the existing key bytes and initialization 
            // vector. Key size will be defined based on the number of the key 
            // bytes.
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                             keyBytes,
                                                             initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream();

            // Define cryptographic stream (always use Write mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                         encryptor,
                                                         CryptoStreamMode.Write);
            // Start encrypting.
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memory stream into a byte array.
            byte[] cipherTextBytes = memoryStream.ToArray();

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert encrypted data into a base64-encoded string.
            string cipherText = Convert.ToBase64String(cipherTextBytes);

            // Return encrypted string.
            return cipherText;
        }

        /// <summary>
        /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </summary>
        /// <param name="cipherText">
        /// Base64-formatted ciphertext value.
        /// </param>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long.
        /// </param>
        /// <param name="keySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        /// Longer keys are more secure than shorter keys.
        /// </param>
        /// <returns>
        /// Decrypted string value.
        /// </returns>
        /// <remarks>
        /// Most of the logic in this function is similar to the Encrypt
        /// logic. In order for decryption to work, all parameters of this function
        /// - except cipherText value - must match the corresponding parameters of
        /// the Encrypt function which was called to generate the
        /// ciphertext.
        /// </remarks>
        public static string Decrypt(string cipherText,
                                     string passPhrase,
                                     string saltValue,
                                     string hashAlgorithm,
                                     int passwordIterations,
                                     string initVector,
                                     int keySize)
        {
            // Convert strings defining encryption key characteristics into byte
            // arrays. Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

            // Convert our ciphertext into a byte array.
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // First, we must create a password, from which the key will be 
            // derived. This password will be generated from the specified 
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                            passPhrase,
                                                            saltValueBytes,
                                                            hashAlgorithm,
                                                            passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate decryptor from the existing key bytes and initialization 
            // vector. Key size will be defined based on the number of the key 
            // bytes.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                             keyBytes,
                                                             initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                          decryptor,
                                                          CryptoStreamMode.Read);

            // Since at this point we don't know what the size of decrypted data
            // will be, allocate the buffer long enough to hold ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            // Start decrypting.
            int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                       0,
                                                       plainTextBytes.Length);

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert decrypted data into a string. 
            // Let us assume that the original plaintext string was UTF8-encoded.
            string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                       0,
                                                       decryptedByteCount);

            // Return decrypted string.   
            return plainText;
        }
    }
}

2

http://sqlserverjunkies.com/HowTo/99201486-ACFD-4607-A0CC-99E75836DC72.dcik 这个类有一个很好的过期日期/时间。 - Christopher G. Lewis

1
创建一个键/值对字符串。加密它。Base64编码它。现在,只需拥有一个名为“x”或其他名称的查询字符串变量,其值将是Base64字符串,像这样:

domain.com/MyPage?x=hfjhwke878979blahblah

然后,您解密并使用它,并将其放回到键/值数据结构中。这是一种方法。


将字符串转换为base64: Convert.ToBase64String(Text.Encoding.ASCII.GetBytes(stringToConvert))将base64转换回字符串: Text.Encoding.ASCII.GetString(Convert.FromBase64String(stringToConvertBack)) - hacker
Base64包含在URL中不允许的字符! - Piotr Perak
考虑到URL字符限制,使用base64不是一个好主意。 - Aimal Khan

0
假设您有一个类似于以下的URL:
www.example.com/customerAdd.aspx?customerId=custId&password=weak

你可以做的是将字符串“customerId=custId&password=weak”使用密钥进行加密,将结果密文编码为base64,现在URL变成了(类似于):
www.example.com/customerAdd.aspx?s=KJADSN1234kNmnanjnads

记得将加密密钥存储在服务器端,不要将其发送到客户端。

现在,如果您对所有加密会话使用相同的密钥,则可以重复使用URL。也就是说,您可以将URL发送给其他人,他们可以访问相同的页面。但是,这种方案会降低您的加密安全性。

如果您为每个会话更改加密密钥,则可以获得额外的安全性,但是会话关闭后URL将无效。


0

尝试构建一个脚本块,例如此页面上的脚本块

它允许您添加一个简单的类并使用简单的密码加密/解密字符串。您可以使用Session.SessionID作为密码。请注意,一旦用户关闭浏览器窗口,链接将不再起作用。

注意:TripleDES不是非常安全,请参阅 Microsoft文章。


当涉及到安全问题时,微软应该保持沉默。 - Nayef

0
您可以使用内置的.NET加密工具对字符串进行加密。您需要在字符串上使用Server.HtmlEncode/Server.HtmlDecode,以确保加密后的字符串符合HTTP标准。 这里是一篇关于.NET加密的文章。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接