Sunday, May 1, 2011

How to get rid of padded zeroes after decryption

This is how I got rid of padded zeroes after using RijndaelManaged encryption:


            // Find the index of the last one appended zero
            int i = plainbytes.Length - 1;
            for (; i > 0; i--)
            {
                  if (plainbytes[i] != 0)
                  {
                        i++;
                        break;
                   }
            }
            // Here i means the number of bytes to take from the array.
            return plainbytes.Take(i).ToArray();


If you turn the byte[] first to string, then you can clean out the string as follows:

            // Find the index of the last one appended zero
            int i = decryptedString.Length - 1;
            for (; i > 0; i--)
            {
                if (decryptedString[i] != '\0')
                {
                    i++;
                    break;
                }
            }
            // Here i means the number of bytes to take from the array.
            decryptedString = decryptedString.Substring(0, i);

No comments:

Post a Comment