0

My program generate AES key, crypt it with rsa algorithm and send to server. But when I fetch it from server and decrypt some bytes become corrupted and replace with sequence 239 191 189 According to this question UTF-8 Encoding and decoding issue I realized that the problem is that server (that also decrypt key) store it as UTF-8 string. Is there any way to create "UTF-8 friendly" keys? There how now generating keys:

 IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CBC/PKCS7Padding"); CipherKeyGenerator aesKeyGenerator = new CipherKeyGenerator(); var rand = new SecureRandom(); aesKeyGenerator.Init(new KeyGenerationParameters(rand, 256)); byte[] key = aesKeyGenerator.GenerateKey(); var aesKey = ParameterUtilities.CreateKeyParameter("AES", _key); var iv = new byte[32]; rand.NextBytes(iv); ParametersWithIV aesKeyParam = new ParametersWithIV(aesKey, iv); 
1
  • 1
    A generated key is probably not text, but a byte array. At least it should be. Don't try converting the key directly to UTF-8. Instead convert the key bytes to characters using Base64. Of course you will need to convert the Base64 back to the original bytes before using it as a key. Commented Jul 6, 2017 at 17:02

1 Answer 1

3

Your AES key consists of bits/bytes. IF you want to view it you could convert the bytes then you should probably use a hexadecimal encoding of those bytes. Generally you do not need to though: AES keys should be kept binary.

Only during debugging does it make sense to convert to hexadecimals. As this is key material it also makes sense to remove those lines after the code is functional - you can perform unit testing with test keys to verify correctness.

It does make sense to convert the RSA encrypted key to base 64 if you need to send the encrypted key over a text interface (SOAP, JSON, XML, whatever). Needless to say you should convert it back into binary upon receiving the wrapped (i.e. encrypted) key.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.