Skip to content

Instantly share code, notes, and snippets.

@ok3141
Created May 15, 2019 09:00
Show Gist options
  • Save ok3141/75eee44f8bd12300999c45ffdbc31fe6 to your computer and use it in GitHub Desktop.
Save ok3141/75eee44f8bd12300999c45ffdbc31fe6 to your computer and use it in GitHub Desktop.
Simple XOR encoder
public class SimpleEncoder {
private static final byte[] SECRET = {
(byte) 0x9e, (byte) 0x40, (byte) 0x5e, (byte) 0xdf,
(byte) 0xd5, (byte) 0x92, (byte) 0x90, (byte) 0x60,
(byte) 0xfe, (byte) 0x4a, (byte) 0xaf, (byte) 0x50,
(byte) 0x74, (byte) 0xed, (byte) 0xcb, (byte) 0x74,
};
public static void xor(@NonNull byte[] input, @NonNull byte[] secret, boolean x) {
if (input.length < 1 || secret.length < 1) {
return;
}
int secretLength = secret.length;
int secretIndex = input.length % secretLength;
for (int i = 0, n = input.length; i < n; ++i) {
int oldValue = (0xff & input[i]);
input[i] ^= secret[secretIndex % secretLength];
int newValue = (0xff & input[i]);
secretIndex = (secretIndex + (x ? oldValue : newValue)) % secretLength;
}
}
@NonNull
public static String toHexString(@NonNull byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
@NonNull
public static byte[] hexToByteArray(@NonNull String input) {
byte[] result = new byte[input.length() / 2];
for (int i = 0, n = input.length(); i < n; i += 2) {
result[i / 2] = (byte) (
(Character.digit(input.charAt(i), 16) << 4) + Character.digit(input.charAt(i + 1), 16)
);
}
return result;
}
@NonNull
public static String encode(@NonNull String input) {
byte[] bytes = input.getBytes();
xor(bytes, SECRET, true);
return toHexString(bytes);
}
@NonNull
public static String decode(@NonNull String input) {
byte[] bytes = hexToByteArray(input);
xor(bytes, SECRET, false);
return new String(bytes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment