This article explains why string Encoding shouldn’t be used to round-trip the cipher text. However, if I try using recommended Convert.ToBase64String, I get an exception if the original string is not packaged with 4-byte blocks. In the following example, the original string doesn’t work, but just “Zoidberg” does, since it’s 8 bytes long (that are packaged into a 6-byte array when Convert.ToBase64String is used).
As promised in the article, if I use any string Encoding, I get “Bad Data” error when decrypting the value back. So how should the original string be fed into the crypto APIs as a byte array?
string text = "Zoidberg is important!"; RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); // This throws FormatException: "The input is not a valid Base-64 string as it // contains a non-base 64 character, more than two padding characters, // or a non-white space character among the padding characters" byte[] cipherText = provider.Encrypt(Convert.FromBase64String(text), false); string plainText = Convert.ToBase64String(provider.Decrypt(cipherText, false));
I think you were mislead by that article.
It does not make sense to convert from
string -> byte[] --> encrypted byte[] --> string, which is what that article is showing you to not do.Presumably, you want to go
string -> byte[] -> encrypted byte[] -> (network, whatever) -> encrypted byte[] -> byte[] -> string.It’s fine to use Encoding to convert the string to bytes in this manner.I don’t know why the article you linked would warn you against taking the encrypted bytes and converting that directly back to a string. Seems silly.
You say you’re trying to round-trip the ciphertext, so I would do so with byte arrays containing the encrypted bytes of your string and forget about base-64 encoding.