2

I have taken the decrypt code from http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.aspx and modified it as follows below. I have an encrypted example, and it works just fine while decoding. But when using the encryption function, it returns junk string with strange symbols. below are the functions of encrypt/decrypt.

An example of encrypted string "hey" : "???U?b???z?Y???"
When decoded again: "ûc{ÁpÅ`ñ""Â"

I'm using this code to convert the byte array to string:

private string ByteArrayToString(byte[] input)
    {
        ASCIIEncoding dec = new ASCIIEncoding();
        return dec.GetString(input);
    }

here are the encrypt/decrypt functions. the decryption function is working fine.

private string DecryptStringFromBytesAes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        // Check arguments. 
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");

        // Declare the string used to hold 
        // the decrypted text.
        string plaintext = null;

        // Create an RijndaelManaged object 
        // with the specified key and IV. 
        using (RijndaelManaged aesAlg = new RijndaelManaged())
        {
            aesAlg.Key = Key;
            aesAlg.Padding = PaddingMode.Zeros;
            aesAlg.Mode = CipherMode.ECB;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for decryption. 
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {

                        // Read the decrypted bytes from the decrypting stream 
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;

    }




private byte[] EncryptStringToBytesAes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments. 
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        byte[] encrypted;
        // Create an RijndaelManaged object 
        // with the specified key and IV. 
        using (RijndaelManaged aesAlg = new RijndaelManaged())
        {
            aesAlg.Key = Key;
            aesAlg.Padding = PaddingMode.Zeros;
            aesAlg.Mode = CipherMode.ECB;
            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption. 
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        return encrypted;

    }
cprogcr
  • 469
  • 2
  • 7
  • 21
  • Well, the primary goal of any encryption process is to convert some meaningful data into something that looks like junk. The more it looks like junk, the better the encryption algorithm is. – Hristo Iliev Jul 27 '12 at 15:22
  • When you say that the encryption function returns junk code do you mean it returns an encrypted string which will look like junk? :-) Encrypted strings will always look "weird" – Shawn Jul 27 '12 at 15:22
  • yeah, it returns strings like ???? and squares too – cprogcr Jul 27 '12 at 15:22
  • lol, thats encryption for you. You could base64 encode it to get rid of the ugly non printing charachters. – Jodrell Jul 27 '12 at 15:24

3 Answers3

4

What you observe is the problem of mapping arbitrary bytes (in the range 0-255) to characters. Meaningful characters are only in the range 32-255 or even only 32-127 (ASCII). Values below 32 are the so-called non-printable characters and values above 127 are dependent on the character encoding you are using. That's why the crypted text looks like junk. Mast crypto-systems therefore transform the bytes into the sensible ASCII-range. One such algorithm is BASE64. So mangling the crypted bytes through BASE64 gives characters that are all printable and that will go without problems through e-mail. Before decrypting you then have to undo the BASE64 encoding.

Another way to make the encrypted result look better is to show the hexa-decimal representation of it. For example if you have a byte value of 15 you print 0F. You may use this to represent your byte array in hex:

private string ByteArrayToHexString(byte[] data)
{
    return String.Concat(data.Select(b => b.ToString("x2")));
}
Stefan Nobis
  • 957
  • 4
  • 12
  • This is correct. Just to clarify to unwary readers Base64 encoding is encoding and not cryptography. Its a way of storing binary in the ASCII range. – Jodrell Jul 27 '12 at 15:30
  • yeah, base64 is a solution, but Jesse C. Slicer comment is what I exactly needed. – cprogcr Jul 27 '12 at 15:37
1

Encrypted strings will look like garble. The way to test if the encryption is working correctly is to pass your string back through decrypt. If it works at decrypting then you know the string is correct despite looking like garbage to you.

Shawn
  • 3,583
  • 8
  • 46
  • 63
  • the encrypted strings must look like this: cfdece55b562efeeb37aa459a013dab3 instead they have strange symbols like ?? and squares – cprogcr Jul 27 '12 at 15:23
  • It depends on the encryption used. Your number above looks like a hash and not an encrypted value. I would try to encrypt and then use decrypt and see if you get your original value. If you do it may just be a character encoding issue in your editor that changes the way you see the encrypted string. Use base 64 encoding. – Shawn Jul 27 '12 at 15:27
  • 2
    @cprogcr So you want hexadecimal output rather than the actual encrypted bytes. See http://stackoverflow.com/a/311179/3312 on how to convert to and from this notation. – Jesse C. Slicer Jul 27 '12 at 15:30
  • @JesseC.Slicer write it as an answer so I can mark it as solved :) It worked btw – cprogcr Jul 27 '12 at 15:35
1

In order to have your output as a hexadecimal encoding of the data, follow the methods found here. I modified them slightly to be extension methods:

    public static string ToHexString(this byte[] bytes)
    {
        return bytes == null ? string.Empty : BitConverter.ToString(bytes).Replace("-", string.Empty);
    }

    public static byte[] FromHexString(this string hexString)
    {
        if (hexString == null)
        {
            return new byte[0];
        }

        var numberChars = hexString.Length;
        var bytes = new byte[numberChars / 2];

        for (var i = 0; i < numberChars; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
        }

        return bytes;
    }
Community
  • 1
  • 1
Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87