I have two numbers: one is an int, other is byte. I want to creat开发者_如何学运维e a single long value out of them in a way that person knowing the byte value can decipher original int from it. Whats the best way to do it?
Assuming i understood your question correct,
The Simplest Solution, You Could XOR the 'int' using the 'byte'
Repeat the process to decrypt...
byte key = 8;
int secret = 123;
System.out.println("Secret : " + secret);
int encrypted = (secret ^ (key | (key << 8)));
System.out.println("Encrypted : " + encrypted );
int decrypt = (encrypted ^ (key | (key << 8)));
System.out.println("Decrypted : " + decrypt );
The result is an 'int' but, you could always just cast it into a long...
long mylong = (((long)mybyte) << 40) | myint;
To retrieve the original value:
int myorigint = (int)(mylong & ~(((long)mybyte) << 40));
But this requires 8-byte longs. Which are not required by the C standard. If a long is 4 bytes, you're out of luck. This means long
and int
would have the same length. If sizeof(int)==sizeof(long)==4
, then asking to store an int and a byte in a long is asking to store 5 arbitrary bytes of information in 4 bytes. Which is completely impossible.
Of course, there's also the trivial "solution":
long mylong = (long)myint;
and the reverse is:
int myint = (int)mylong;
Now, someone knowing (or not knowing!) the byte can retrieve the original data.
If you want a solution such that only someone knowing the correct byte can retrieve the original int, you can use this:
long mylong = (long)(myint-mybyte);
and reverse:
int myint = (int)(mylong+mybyte);
But know that encrypting four bytes with one byte will not be truly secure. You should use a 4-byte one-time pad to encrypt four bytes. If you have a four-byte key, use XOR for a truly unbreakable cipher. No, really.
One idea is to apply a reversible function the number of times indicated by the byte.
To get the original number back just apply the inverse function the same number of times.
e.g.
public static int encrypt(int value, byte key) {
int result=value;
for (int i=0; i<=(key&255); i++) {
result=Integer.rotateRight(result,7)^(i+0xCAFEBABE);
}
return result;
}
Finding the reverse function left as an exercise for the reader.....
精彩评论