Click here to Skip to main content
14,454,912 members
Rate this:
Please Sign up or sign in to 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
Rate this:
Please Sign up or sign in to vote.

Solution 1

That's because you're not encrypting - you're hashing - and you can't un-hash something.
   
Comments
   
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
Rate this:
Please Sign up or sign in to vote.

Solution 4

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.
   
Comments
   
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.
Rate this:
Please Sign up or sign in to vote.

Solution 2

MD5 is a one way hashing algorithm so it cannot be decrypted.
   
Comments
   
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
Rate this:
Please Sign up or sign in to vote.

Solution 3

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
   
v5
Comments
NuttingCDEF 5-May-11 15:31pm
   
Good answer - my 5 - and 5 for the others too!
   
Thank you very much.
--SA
FIRMANSYAH.MS 5-May-11 15:33pm
   
thank you so much for the solution :)
   
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.
   
You are absolutely right, of cause. I just gave a first example straight out of my hand. To get into more detail, OP should see what System.Security.Cryptography offers but thoroughly understand the purpose of every of the tools. I'll add a note to my solution.
--SA
   
Answer updated.
Thanks for your notes and the discussion.
--SA
Wonde Tadesse 5-May-11 21:50pm
   
Sometimes it is better to give sample code, rather than showing a bunch of article links.
   
Yes, but why should I write this code? OP did not even ask about it. The OP code makes no sense, so it cannot be fixed; and there is no any certain requirements to know.

By the way, if you criticize me on this matter, it makes me impression you address to a wrong person. Are you sure?
If you simply want to bring you solution to my attention -- just write so in your comment -- there is nothing wrong about it. I up-voted your solution, by the way.

Cheers,
--SA
Wonde Tadesse 7-May-11 21:55pm
   
I'm not criticizing on the matter. But the member asks a question regarding encryption and decryption, emphasizing on his attempt will not resolve the question.

Peace.
   
This matter is covered in the update after [EDIT].
The original question was completely resolver is first place: the answer to the problem on inability to "decrypt" the hash is: impossible. What to do is the different question; one of the ways to address encryption is RSA. OP did not provide any requirements though.
--SA

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100