[英]Using java to encrypt integers
我正在尝试使用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--
//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
我找到了以下可能对您有帮助的代码,因为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
只需使用:
Integer.toString(int).getBytes();
确保使用原始int,getBytes()将返回一个字节数组。 不需要做任何复杂的事情。
要转换回来:
Integer.parseInt(encryptedString);
保罗说,创建一个4字节的数组,然后用4个步骤将int复制到数组中,使用按位AND和位移。
但请记住,诸如AES和DES之类的块算法可以使用8或16字节块,因此您需要将数组填充到算法所需的内容中。 也许将8字节数组的前4个字节保留为0,其他4个字节包含整数。
我的简单解决方案是通过将您提供的密钥移位整数的ASCII值来将整数加密到字符串。
这是解决方案:
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;
}
编码步骤:
String temp = givenInt + ""
定的整数转换为字符串: String temp = givenInt + ""
Integer
转换为Character并连接到String encryptNum
并最终返回它。 解码步骤:
decodeText
连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.