2008-11-26 35 views
6

我想使用java.security和javax.crypto加密java中的一些整數。使用java來加密整數

問題似乎是Cipher類只加密字節數組。我不能直接將整數轉換爲字節字符串(或者我可以嗎?)。做這個的最好方式是什麼?

我應該將整數轉換爲一個字符串,並將字符串轉換爲byte []?這似乎太低效了。

有沒有人知道一個快速/簡單或有效的方法來做到這一點?

請讓我知道。

在此先感謝。

JBU

+0

嗯..你在不同字節之間回事?如果這樣會導致這些整數在將它們從字節數組轉換回來時不正確。 – SCdF 2008-11-26 19:19:10

+0

很明顯,「Java虛擬機總是使用big-endian」,所以我想這不是問題。 – SCdF 2008-11-26 19:20:46

回答

12

你可以把整型成使用DataOutputStream類一個byte [],就像這樣:

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

再到後來解密:

byte[] decrypted = decrypt (data); 
ByteArrayInputStream bais = new ByteArrayInputStream (data); 
DataInputStream dis = new DataInputStream (bais); 
int j = dis.readInt(); 
3

我發現以下代碼可以幫助你,因爲Java中的Integer總是4個字節。

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

您可以找到有關大尾端參數這裏的更多信息: http://en.wikipedia.org/wiki/Endianness

9

您還可以使用BigInteger的轉換:

BigInteger.valueOf(integer).toByteArray(); 
5

只需使用NIO。它是爲這個特定的目的而設計的。 ByteBuffer和IntBuffer可以快速,高效,優雅地完成你所需要的任務。它將處理大/小端轉換,用於高性能IO的「直接」緩衝區,甚至可以將數據類型混合到字節緩衝區中。

轉換整數成字節:

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 

轉換字節到整數:

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

創建一個4字節陣列和INT複製到陣列中的4個步驟,以按位AND和移位,就像Paulo說的那樣。

但請記住,像AES和DES這樣的塊算法可以處理8或16字節的塊,因此您需要將陣列填充到算法所需的位置。也許將8字節數組的前4個字節保留爲0,而其他4個字節保留整數。

0

只需使用:

Integer.toString(int).getBytes(); 

確保你使用你原來的int和的getBytes()將返回一個字節數組。無需做任何其他複雜的事情。

要轉換回:

Integer.parseInt(encryptedString);