Click here to Skip to main content
15,885,125 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
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?
Posted

That's because you're not encrypting - you're hashing - and you can't un-hash something.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-May-11 15:24pm    
I said the same at the same time. 5 for the answer.
I also suggest how to do encryption.
--SA
FIRMANSYAH.MS 5-May-11 15:34pm    
thank you very much for your answer
Here is what you looking for my friend.

C#
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.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-May-11 23:04pm    
I did not test it, but looks correct, my 5.

Just one advice: do not put region name in quotation marks -- it you try to search all strings by '"' it makes false-positive finds.
--SA
Wonde Tadesse 7-May-11 21:49pm    
Thanks for your advice. I usually don't use quotation mark. It just happens only for this case.
MD5 is a one way hashing algorithm so it cannot be decrypted.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-May-11 15:27pm    
I said the same at the same time. 5 for this answer.
I also suggest how to do encryption.
--SA
FIRMANSYAH.MS 5-May-11 15:34pm    
thank you very much for your answer
Who told you that you can "decrypt" the hash?! A hashing algorithm cannot be reversed, according to its purpose.

(Also, you should never use MD5 for any security purpose. This algorithm is considered broken. The algorithms of of SHA family is recommended instead. Both are supported by .NET.
See http://en.wikipedia.org/wiki/MD5[^], http://en.wikipedia.org/wiki/SHA2[^].)

This has nothing to do with encryption. Use, for example, RSA; it is perfectly supported by .NET.
See:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsa.aspx[^],
http://en.wikipedia.org/wiki/Asymmetric_key_algorithm[^],
http://en.wikipedia.org/wiki/RSA[^].

[EDIT]

RSA is just one example you can use for both encryption and digital signatures. You need to look at System.Security.Cryptography and thoroughly understand the purpose of each tool. See:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx[^].

Start here:
http://msdn.microsoft.com/en-us/library/92f9ye3s.aspx[^].

—SA
 
Share this answer
 
v5
Comments
NuttingCDEF 5-May-11 15:31pm    
Good answer - my 5 - and 5 for the others too!
Sergey Alexandrovich Kryukov 5-May-11 15:36pm    
Thank you very much.
--SA
FIRMANSYAH.MS 5-May-11 15:33pm    
thank you so much for the solution :)
Sergey Alexandrovich Kryukov 5-May-11 15:35pm    
You're welcome.
If you find it useful, please formally accept this answer (green button).
Thank you.
--SA
NuttingCDEF 5-May-11 15:40pm    
P.S. Is it also worth mentioning:

1. The distinction between symmetric and asymmetric key ciphers and why / when you'd use one rather than the other.

2. That hashes have their uses including how to use / store strong passwords securely and salts.

3. Other cryptographic tools such as signing, certificates and key exchange.

Encryption is an excellent tool, but if you don't know how to use it properly it can give a false sense of security.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900