Search code examples
javaencryptionbouncycastle

How to encrypt arbitrary data types using BouncyCastle?


Can anyone show me an example of how to do encryption in Java using BouncyCastle (or similar API) for data types other than String?

I want to encrypt other Java types like Integer, Double and Date etc. I've looked over bouncycastle.org but cannot find any documentation of their API.


Solution

  • Encryption is an operation that is always performed on binary data. Any examples you've seen that work with String objects will be converting those strings into byte arrays at some point during the process.

    The goal is to define a canonical method of converting your data into a byte array representation. Once you have this, you can use example code found all over the Internet to perform the encryption.

    You may wish to convert an Integer into a four byte array, for example. Perhaps using code such as:

    ByteBuffer.allocate(4).putInt(integerValue).array()
    

    A Date might be best converted to a UNIX timestamp and then converted to a byte array using the code above.

    The recipient of your encrypted data must understand how you serialised it to a byte array so that they can reverse the process. Note that in the case of strings, it's important both sides agree on a charset used when converting to/from a byte array.