Using java to encrypt integers

后端 未结 7 1630
野性不改
野性不改 2021-02-03 14:14

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 d

7条回答
  •  遇见更好的自我
    2021-02-03 15:13

    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

提交回复
热议问题