加密和解密数据 [英] Encrypt and decrypt data

查看:95
本文介绍了加密和解密数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想加密和解密数据,在一个ASP.net入门工具包中,我发现可以使用以下方法进行加密:

Hi
I want to encrypt and decrypt data, and in one of ASP.net Starter Kits, i found that you can encrypt using the following method:

public static string Encrypt(string cleanString)
{
Byte[] clearBytes = new UnicodeEncoding().GetBytes(cleanString);
Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);

return BitConverter.ToString(hashedBytes);

}
string EncryptedData = Encrypt(CleanData);



我的问题是我无法解密数据,任何人都有任何想法吗?



My problem is that i cannot decrypt the data, anyone has any ideas?

推荐答案

那是因为您未加密-您正在散列-并且您不能取消哈希操作.
That''s because you''re not encrypting - you''re hashing - and you can''t un-hash something.


这是您在寻找我的朋友的内容.

Here is what you looking for my friend.

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// Encryptor class
/// </summary>
/// <remarks></remarks>
public sealed class Encryptor
{

    #region " Private Static Members "

    private static byte[] _savedKey = null;

    private static byte[] _savedIV = null;

    #endregion

    #region " Private Static Methods "

    /// <summary>
    /// Generate Secret Key and Initial Vector
    /// </summary>
    /// <remarks></remarks>
    private static void generateSecretKeyAndInitVector()
    {
        dynamic keyGen = new Rfc2898DeriveBytes("9be6ee5b-e76b-4d4d-86b9-20284fe6ba96", Encoding.ASCII.GetBytes("8726a597-eabe-4b0a-990f-29956dbb5e4a"));
        _savedKey = keyGen.GetBytes(32);
        _savedIV = keyGen.GetBytes(16);
    }

    #endregion

    #region " Public Static Methods "

    /// <summary>
    /// Encrypt PlainText value
    /// </summary>
    /// <param name="plainText">PlainText value</param>
    /// <returns>CipherText value</returns>
    /// <remarks></remarks>
    public static string Encrypt(string plainText)
    {
        // Encode data string to be stored in memory.
        byte[] plainTextAsBytes = Encoding.ASCII.GetBytes(plainText);
        byte[] cipherTextAsBytes = {
        };

        // Create MemoryStream to contain output.
        using (MemoryStream memStream = new MemoryStream(plainTextAsBytes.Length))
        {
            using (RijndaelManaged rijndael = new RijndaelManaged())
            {

                // Generate and save secret key and init vector.
                generateSecretKeyAndInitVector();

                if (_savedKey == null || _savedIV == null)
                {
                    throw new NullReferenceException("savedKey and savedIV must be non-null.");
                }

                // Create encryptor and stream objects.
                using (ICryptoTransform rdTransform = rijndael.CreateEncryptor((byte[])_savedKey.Clone(), (byte[])_savedIV.Clone()))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform, CryptoStreamMode.Write))
                    {
                        // Write encrypted data to the MemoryStream.
                        cryptoStream.Write(plainTextAsBytes, 0, plainTextAsBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        cipherTextAsBytes = memStream.ToArray();
                    }
                }
            }
        }
        // Convert encrypted string.
        string cipherText = Convert.ToBase64String(cipherTextAsBytes);
        return cipherText;
    }

    /// <summary>
    /// Decrypt CipherText value
    /// </summary>
    /// <param name="cipherText">CipherText value</param>
    /// <returns>Planetext value</returns>
    /// <remarks></remarks>
    public static string Decrypt(string cipherText)
    {
        // Unconvert encrypted string.
        byte[] cipherTextAsBytes = Convert.FromBase64String(cipherText);
        byte[] planeTextAsBytes = new Byte[cipherTextAsBytes.Length];

        // Generate and save secret key and init vector.
        generateSecretKeyAndInitVector();

        using (RijndaelManaged rijndael = new RijndaelManaged())
        {
            using (MemoryStream memStream = new MemoryStream(cipherTextAsBytes))
            {
                if (_savedKey == null || _savedIV == null)
                {
                    throw new NullReferenceException("savedKey and savedIV must be non-null.");
                }

                // Create decryptor, and stream objects.
                using (ICryptoTransform rdTransform = rijndael.CreateDecryptor((byte[])_savedKey.Clone(), (byte[])_savedIV.Clone()))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memStream, rdTransform, CryptoStreamMode.Read))
                    {
                        // Read in decrypted string as a byte[].
                        cryptoStream.Read(planeTextAsBytes, 0, planeTextAsBytes.Length);
                    }
                }
            }
        }

        // Convert byte[] to string.
        string planeText = Encoding.ASCII.GetString(planeTextAsBytes);
        return planeText;
    }

    #endregion

}



祝您好运.



Good luck.


MD5是一种单向哈希算法,因此无法解密.
MD5 is a one way hashing algorithm so it cannot be decrypted.


这篇关于加密和解密数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆