Created
September 6, 2023 22:39
-
-
Save gigamonkey/732b4d3bbbe74ac937542522547dfd0d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.charset.StandardCharsets; | |
public class Xor { | |
// This is the cipher text, encoded as a hex string. If you translate every two | |
// characters of this string into a byte you will have an array of bytes which | |
// can be decoded by xor'ing the bytes with bits from the key, taking first the 8 | |
// least significant bits of the key for the 0th byte, the the next 8, and so on, | |
// looping back around to the least significant bits every four bytes. | |
private static final String CIPHERTEXT = | |
"452dbb017333a6456328a64f6064a6522722ba4f26"; | |
// This is the key. It is just a random int, so 32 random bits. It was used to | |
// encode my secret message converted to bytes with msg.getBytes("UTF-8") | |
private static final int KEY = 567231495; | |
public static void main(String[] argv) throws Exception { | |
System.out.println(new Xor().decode(CIPHERTEXT, KEY)); | |
} | |
/* | |
* Convert a string representing a hex-encoded array of bytes to an actual | |
* array of bytes. | |
*/ | |
public byte[] fromHexString(String s) { | |
var bytes = new byte[s.length() / 2]; | |
for (var i = 0; i < bytes.length; i++) { | |
bytes[i] = (byte) Integer.parseInt(s.substring(i * 2, (i + 1) * 2), 16); | |
} | |
return bytes; | |
} | |
/* | |
* Encrypt/decrypt plaintext bytes using an int key. (It's symmetric.) | |
*/ | |
public byte[] xor(byte[] plaintext, int key) { | |
var ciphertext = new byte[plaintext.length]; | |
for (var i = 0; i < plaintext.length; i++) { | |
ciphertext[i] = (byte) (plaintext[i] ^ (key >>> (8 * (i % 4)))); | |
} | |
return ciphertext; | |
} | |
/* | |
* Decode hex string and then decrypt the resulting bytes and make into a String. | |
*/ | |
public String decode(String encoded, int key) { | |
return new String(xor(fromHexString(encoded), key), StandardCharsets.UTF_8); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment