XOR has almost magical properties:
if ( condition ) { toggle = ! toggle; }You can code it more tersely like this:
toggle ^= condition;Further, the generated byte code for the xor version will be more compact, and the generated machine code will execute more quickly.
// encrypting a[] with key k[] into e[] // a[] = array to be encrypted // k[] = key of truly random gibberish // e[] = encrypted data byte[] e = new byte[a.length]; for ( int i=0; i<a.length; i++ ) { e[i] = (byte)( a[i] ^ k[i] ); }Someone peeking at e[] who has no copy of k[] has no way on earth of guessing what a[] is. Every possible encryption of every possible message is equally probable. The decrytped message could equally well say, "plan B tonight at seven" or "The Snow Queen---------". You could get either result just using two different decrypting keys. Who is to say which is the real one? To decrypt, you use xor again with the same k[]:
// decrypting e[] with key k[] into a[] // e[] = array to be decrypted // k[] = key of truly random gibberish // a[] = original data byte[] a = new byte[e.length]; for ( int i=0; i<e.length; i++ ) { a[i] = (byte)( e[i] ^ k[i] ); }For this to be secure, you must never reuse a key k. A pre-computer era version of this was known as the Vernam cipher. It is used for diplomatic messages that absolutely must not be cracked. The main problem with it is you somehow have to get the keys to the other end without them being viewed. You can do that with CD and secure courier. If you suspect compromise, you don’t use the keys. You need software to make sure you never reuse a key.
| You can get the freshest copy of this page from: | or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror) | |
| http://mindprod.com/jgloss/xor.html | J:\mindprod\jgloss\xor.html | |
![]() | ||
| Canadian Mind Products | ||
| mindprod.com IP:[65.110.21.43] | ||
| view Blog | Your face IP:[38.107.191.104] | |
| Feedback | You are visitor number 110,458. | |