Question

I am encoding strings using C#'s Rijndael AES encryption. I generate a key and an IV, and use them to encode strings and values that I can then save to disk (I am using Unity3D's playerprefs).

The problem I am facing is that the PlayerPrefs keys and values need to be valid character sequences, and the encoded bytes are not necessarily valid.

So, after encoding my string with my key and IV, I get a byte array that I can enode in Unicode, but (sometimes) when I try to save it, I get an error message:

byte[] encryptedBytes = Encode("someText", encryptionKey, initVector);
string encodedString = Encoding.Unicode.GetString(encryptedBytes);
PlayerPrefs.SetString("SecretData",encodedString);
PlayerPrefs.Save();

Error:

invalid utf-16 sequence at -1073752512 (missing surrogate tail)

Any way to make sure the string is in a valid format?

Was it helpful?

Solution

The bytes returned by the encrypt function are indistinguishable from random and may not contain valid character encoding. To convert the result into a string (if required) you may use base 64.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top