7

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

2
  • Hmm.. are you going between different Endianness? If so that would cause those integers to be incorrect when you converted them back from the byte array.. Commented Nov 26, 2008 at 19:19
  • Apparerntly "Java virtual machine always used big-endian", so I guess it's not an issue. Commented Nov 26, 2008 at 19:20

7 Answers 7

11

You can turn ints into a byte[] using a DataOutputStream, like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream ();
DataOutputStream dos = new DataOutputStream (baos);
dos.writeInt (i);
byte[] data = baos.toByteArray();
// do encryption

Then to decrypt it later:

byte[] decrypted = decrypt (data);
ByteArrayInputStream bais = new ByteArrayInputStream (data);
DataInputStream dis = new DataInputStream (bais);
int j = dis.readInt();
Sign up to request clarification or add additional context in comments.

Comments

9

You can also use BigInteger for conversion:

 BigInteger.valueOf(integer).toByteArray();

1 Comment

you're creating an un needed intermediate string object in this process.
5

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:

ByteBuffer bbuffer = ByteBuffer.allocate(4*theIntArray.length);
IntBuffer ibuffer = bbuffer.asIntBuffer(); //wrapper--doesn't allocate more memory
ibuffer.put(theIntArray);                  //add your int's here; can use 
                                           //array if you want
byte[] rawBytes = bbuffer.array();         //returns array backed by bbuffer--
                                           //i.e. *doesn't* allocate more memory

Convert bytes into integers:

ByteBuffer bbuffer = ByteBuffer.wrap(rawBytes);
IntBuffer ibuffer = bbuffer.asIntBuffer();
while(ibuffer.hasRemaining())
   System.out.println(ibuffer.get());      //also has bulk operators

Comments

3

I have found the following code that may help you, since Integer in Java is always 4 bytes long.

public static byte[] intToFourBytes(int i, boolean bigEndian) {  
    if (bigEndian) {  
        byte[] data = new byte[4];  
        data[3] = (byte) (i & 0xFF);  
        data[2] = (byte) ((i >> 8) & 0xFF);  
        data[1] = (byte) ((i >> 16) & 0xFF);  
        data[0] = (byte) ((i >> 24) & 0xFF);  
        return data;  

    } else {  
        byte[] data = new byte[4];  
        data[0] = (byte) (i & 0xFF);  
        data[1] = (byte) ((i >> 8) & 0xFF);  
        data[2] = (byte) ((i >> 16) & 0xFF);  
        data[3] = (byte) ((i >> 24) & 0xFF);  
        return data;  
    }  
}  

You can find more information about the bigEndian parameter here: http://en.wikipedia.org/wiki/Endianness

Comments

0

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.

Comments

-1

Just use:

    Integer.toString(int).getBytes();

Make sure you use your original int and getBytes() will return a byte array. No need to do anything else complicated.

To convert back:

    Integer.parseInt(encryptedString);

Comments

-1

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:

public String encodeDiscussionId(int Id) {

    String tempEn = Id + "";
    String encryptNum ="";
    for(int i=0;i<tempEn.length();i++) {
        int a = (int)tempEn.charAt(i);
        a+=148113;
        encryptNum +=(char)a;
    }
    return encryptNum;
}

public Integer decodeDiscussionId(String encryptText) {

    String decodeText = "";
    for(int i=0;i<encryptText.length();i++) {
        int a= (int)encryptText.charAt(i);
        a -= 148113;
        decodeText +=(char)a;
    }
    int decodeId = Integer.parseInt(decodeText);
    return decodeId;
}

Steps to Encode:

  1. Here, First you convert the Given Integer into String by: String temp = givenInt + ""
  2. Scan each character of String, Read ASCII of that character and add it with secret key as 148113 in this case.
  3. Convert shifted Integer into Character and concatenate to the String encryptNum and finally return it.

Steps to Decode:

  1. Scan each character of String, Read ASCII of that character and subtract it with secret key as previous.
  2. Convert that value to character and concatenate with decodeText.

As previous encode output is always String '???' and vary according to number of digits of input Id.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.