I'm trying to encrypt some integers in java using java.security and javax.crypto.
The problem seems to be that the Cipher class only encrypts byte arrays. I can't directly convert an integer to a byte string (or can I?). What is the best way to do this?
Should I convert the integer to a string and the string to byte[]? This seems too inefficient.
Does anyone know a quick/easy or efficient way to do it?
Please let me know.
Thanks in advance.
jbu
You can also use BigInteger for conversion:
Just use NIO. It's designed for this specific purpose. ByteBuffer and IntBuffer will do what you need quickly, efficiently, and elegantly. It'll handle big/little endian conversion, "direct" buffers for high performance IO, and you can even mix data types into the byte buffer.
Convert integers into bytes:
Convert bytes into integers:
My Simple Solution is that Encrypt Integer to the String by shifting ASCII Value of the Integer by the secret key you Provide.
Here is the Solution:
Steps to Encode:
String temp = givenInt + ""
Integer
into Character and concatenate to theString encryptNum
and finally return it.Steps to Decode:
decodeText
.As previous encode output is always
String '???'
and vary according to number of digits of inputId
.I have found the following code that may help you, since Integer in Java is always 4 bytes long.
You can find more information about the bigEndian parameter here: http://en.wikipedia.org/wiki/Endianness
Just use:
Make sure you use your original int and getBytes() will return a byte array. No need to do anything else complicated.
To convert back:
create a 4-byte array and copy the int to the array in 4 steps, with bitwise ANDs and bitshifting, like Paulo said.
But remember that block algorithms such as AES and DES work with 8 or 16 byte blocks so you will need to pad the array to what the algorithm needs. Maybe leave the first 4 bytes of an 8-byte array as 0's, and the other 4 bytes contain the integer.