0

On my Blackberry I am creating an AES key and encrypting data. I am then encrypting the AES key with RSA before sending to the client c#.net

The AES key is a byte array. How can I convert this to a string so that it can be encrypted by RSA and then decrypted on the .net side?

Do I have to convert to string?

I am transmitting the data via JSON. I guess my question is really how to transmit a but array in JSON? What character encoding would I use?

Thanks.

jim
  • 8,670
  • 15
  • 78
  • 149

1 Answers1

1

You can use the following, which is URL safe and relatively easy to visually inspect. This takes a little more storage than Convert.ToBase64String, but shouldn't be an issue with a fixed width encryption key.

string MyKey = BitConverter.ToString(MyAESKey);  // dash removal is trivial here

OR

string MyKey = Convert.ToBase64String(MyAESKey);

Code Sample

byte[] a = new byte[256/8];
Random random = new Random();
random.NextBytes(a);

string base64 = Convert.ToBase64String(a);
byte [] b = Convert.FromBase64String(base64);

if (a.SequenceEqual(b))
    // true


string c = BitConverter.ToString(a);

string[] c1 = c.Split('-');
byte[] d = new byte[arr.Length];
for (int i = 0; i < arr.Length; i++) d[i] = Convert.ToByte(c1[i], 16);

if (a.SequenceEqual(d))
    // true
Jeremy Gray
  • 1,378
  • 1
  • 9
  • 24
  • Hmm, just tried that, thanks. But I have a problem. When I convert my 256 element byte array from java to Base64 it's longer than 256.. (290 or something). But when I convert it back in .NET it stays that length. Why is that? Thanks. – jim Mar 13 '12 at 18:50
  • Ok, but when I do a base64 decode shouldn't the data be identical to before it was encoded? In my case it's not, the decoded data bytes array is longer than the original :-/ – jim Mar 13 '12 at 19:06
  • There are a couple reasons, the easiest in general is b/c you are representing your universe in in a base 64 system...so non printable characters need more encoding space. What is most likely going on in this situation has to do with how the encoding actually works. The method encodes each set of 3 bytes into 4 bytes and the output is always padded to be a multiple of 4. So your expansion formula will be ceil(n / 3) * 4, where n is the number of bytes in your input. – Jeremy Gray Mar 13 '12 at 19:10
  • It's all good now, while examining my code to see what to post I spotted a typo. Thanks guys. – jim Mar 13 '12 at 20:22
  • 1
    Why bother base64 encoding the input to RSA? It doesn't make any sense. – President James K. Polk Mar 13 '12 at 21:21
  • And why is your byte array 256 bytes long? That's enough to hold 8 256 bit keys. – Maarten Bodewes Mar 14 '12 at 20:15