我希望确保对严格正长的XOR操作只产生严格的正长。
我的问题是基于以下java代码:
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
public class Test {
static Random r = new Random();
static class Data {
long id = Math.abs(r.nextLong());
@Override
public String toString() {
return "Data {" + "id=" + id + '}';
}
}
public static void main(String[] args) {
List<Data> data = new ArrayList<>();
for (int i = 0; i < 10; i++) {
data.add(new Data());
}
final String password = "don't you ever tell them";
byte[] passwordBytes = password.getBytes();
long[] passwordLongs = new long[passwordBytes.length / 8];
for (int i = 0; i < passwordLongs.length; i++) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
byte[] chunk = new byte[Long.BYTES];
System.arraycopy(passwordBytes, i * Long.BYTES, chunk, 0, Long.BYTES);
buffer.put(chunk);
buffer.flip();//need flip
passwordLongs[i] = buffer.getLong();
}
System.out.println(data);
ListIterator<Data> encryptIterator = data.listIterator();
while (encryptIterator.hasNext()) {
Data next = encryptIterator.next();
next.id = next.id ^ passwordLongs[(encryptIterator.nextIndex() - 1) % passwordLongs.length];//XOR here
}
System.out.println(data);
}
}有谁能给出一个答案,可能有一些理论吗?
发布于 2015-10-04 09:15:56
结论:正整数XOR正整数=正整数。
发布于 2015-10-04 09:23:21
考虑到Java中的longs总是被签名的,您应该确保您的“密码”中的每个long都不会切换符号位。
也就是说,long中的所有password都应该像0b0xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx一样。
这稍微削弱了“加密”(确切地说),但您不应该太担心这一点。
但是,应该注意的是,除非要比较它们大于0,否则没有理由这样做;实际数字总是相同的,也就是说,0xff或0b11111111总是相同的,只有它的十进制表示形式根据使用无符号或有符号的短整数来存储它而改变(255和-1 )。
https://stackoverflow.com/questions/32931867
复制相似问题