Search code examples
c#encryptionutf-8bouncycastle

Convert Bouncy castle aes key to UTF-8 string


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);

Solution

  • 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.