用java加密整数
我正在尝试使用java.security和javax.crypto加密java中的一些整数。
问题似乎是Cipher类只加密字节数组。 我不能直接将整数转换为字节串(或者我可以?)。 做这个的最好方式是什么?
我应该将整数转换为字符串,将字符串转换为byte []吗? 这似乎效率太低。
有谁知道快速/简单或有效的方法吗?
请告诉我。
提前致谢。
JBU
您可以使用DataOutputStream将ints转换为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();
您还可以使用BigInteger进行转换:
BigInteger.valueOf(integer).toByteArray();
只需使用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-- //ie *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
我发现以下代码可能对您有所帮助,因为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; } }
您可以在此处找到有关bigEndian参数的更多信息: http : //en.wikipedia.org/wiki/Endianness
保罗说,创建一个4字节的数组,并以4个步骤将int复制到数组中,使用按位AND和位移。
但请记住,AES和DES等块算法可以使用8或16字节块,因此您需要将数组填充到算法所需的位置。 也许将8字节数组的前4个字节保留为0,其他4个字节包含整数。
只需使用:
Integer.toString(int).getBytes();
确保使用原始int,getBytes()将返回一个字节数组。 不需要做任何其他复杂的事情。
要转换回来:
Integer.parseInt(encryptedString);
我的简单解决方案是通过将您提供的密钥移位整数的ASCII值来将整数加密到字符串。
这是解决方案:
public String encodeDiscussionId(int Id) { String tempEn = Id + ""; String encryptNum =""; for(int i=0;i
编码步骤:
- 在这里,首先您
String temp = givenInt + ""
定的整数转换为字符串:String temp = givenInt + ""
- 在这种情况下,扫描字符串的每个字符,读取该字符的ASCII并使用密钥添加为148113。
- 将移位的
Integer
转换为Character并连接到String encryptNum
并最终返回它。
解码步骤:
- 扫描字符串的每个字符,读取该字符的ASCII,并使用前一个密钥减去它。
- 将该值转换为字符并与
decodeText
连接。
因为以前的编码输出总是String '???'
并根据输入Id
的位数而变化。