Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Simple demo of single-bit encryption. Not for production use, just a
- * quick, hacked-up demo.
- */
- public class LameSinglebitEncryption {
- public static final String SEPARATOR = "-";
- private enum Operation {Encrypt, Decrypt};
- // This is the actual "encrypt/decrypt" operation itself. Everything else is just glue.
- private static byte[] applySingleBitXor(byte[] content, byte[] key) {
- byte[] xorBytes = new byte[content.length];
- for(int i = 0; i < content.length; ++i) {
- xorBytes[i] = (byte) (content[i] ^ key[i % key.length]);
- }
- return xorBytes;
- }
- private static void outputEncrypted(byte[] content) {
- for(int i = 0; i < content.length; ++i) {
- if(i > 0) System.out.print(SEPARATOR);
- System.out.print(content[i]);
- }
- System.out.println();
- }
- private static byte[] parseEncrypted(String encrypted) {
- String[] rawStrings = encrypted.split(SEPARATOR);
- byte[] content = new byte[rawStrings.length];
- for(int i = 0; i < rawStrings.length; ++i) {
- content[i] = Byte.parseByte(rawStrings[i]);
- }
- return content;
- }
- public static void main(String[] args) {
- try {
- String cmd = args[0];
- String key = args[1];
- String str = args[2];
- Operation op = Operation.valueOf(cmd);
- System.out.println(op + "ing [" + str + "] using key [" + key + "]");
- if(op == Operation.Encrypt) {
- byte[] encBytes = applySingleBitXor(str.getBytes(), key.getBytes());
- outputEncrypted(encBytes);
- } else if(op == Operation.Decrypt) {
- byte[] unencBytes = applySingleBitXor(parseEncrypted(str), key.getBytes());
- System.out.println(new String(unencBytes));
- } else {
- throw new Exception("...the fuck?");
- }
- } catch(Exception ex) {
- System.out.println("This not a lesson in proper input validation and exception-handling... " + ex.getMessage());
- ex.printStackTrace();
- System.out.println("Usage: java LameSinglebitEncryption [Encrypt|Decrypt] key string-to-transform");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement