用java加密整数

jbu*_*jbu 6 java encryption integer cryptography bytearray

我正在尝试使用java.security和javax.crypto加密java中的一些整数.

问题似乎是Cipher类只加密字节数组.我不能直接将整数转换为字节字符串(或者我可以?).做这个的最好方式是什么?

我应该将整数转换为字符串,将字符串转换为byte []吗?这看起来效率太低了.

有谁知道快速/简单或有效的方法吗?

请告诉我.

提前致谢.

JBU

jod*_*ell 12

您可以使用DataOutputStream将ints转换为byte [],如下所示:

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

然后再解密它:

byte[] decrypted = decrypt (data);
ByteArrayInputStream bais = new ByteArrayInputStream (data);
DataInputStream dis = new DataInputStream (bais);
int j = dis.readInt();
Run Code Online (Sandbox Code Playgroud)


asa*_*n74 9

您还可以使用BigInteger进行转换:

 BigInteger.valueOf(integer).toByteArray();
Run Code Online (Sandbox Code Playgroud)


Jam*_*hek 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
Run Code Online (Sandbox Code Playgroud)

将字节转换为整数:

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