Advertisement
Guest User

Single-bit encryption demo

a guest
Jul 1st, 2012
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | None | 0 0
  1. /**
  2.  * Simple demo of single-bit encryption. Not for production use, just a
  3.  * quick, hacked-up demo.
  4.  */
  5. public class LameSinglebitEncryption {
  6.     public static final String SEPARATOR = "-";
  7.     private enum Operation {Encrypt, Decrypt};
  8.  
  9.     // This is the actual "encrypt/decrypt" operation itself. Everything else is just glue.
  10.     private static byte[] applySingleBitXor(byte[] content, byte[] key) {
  11.         byte[] xorBytes = new byte[content.length];
  12.         for(int i = 0; i < content.length; ++i) {
  13.             xorBytes[i] = (byte) (content[i] ^ key[i % key.length]);
  14.         }
  15.         return xorBytes;
  16.     }
  17.  
  18.     private static void outputEncrypted(byte[] content) {
  19.         for(int i = 0; i < content.length; ++i) {
  20.             if(i > 0) System.out.print(SEPARATOR);
  21.             System.out.print(content[i]);
  22.         }
  23.         System.out.println();
  24.     }
  25.  
  26.     private static byte[] parseEncrypted(String encrypted) {
  27.         String[] rawStrings = encrypted.split(SEPARATOR);
  28.         byte[] content = new byte[rawStrings.length];
  29.         for(int i = 0; i < rawStrings.length; ++i) {
  30.             content[i] = Byte.parseByte(rawStrings[i]);
  31.         }
  32.         return content;
  33.     }
  34.  
  35.     public static void main(String[] args) {
  36.         try {
  37.             String cmd = args[0];
  38.             String key = args[1];
  39.             String str = args[2];
  40.  
  41.             Operation op = Operation.valueOf(cmd);
  42.  
  43.             System.out.println(op + "ing [" + str + "] using key [" + key + "]");
  44.  
  45.             if(op == Operation.Encrypt) {
  46.                 byte[] encBytes = applySingleBitXor(str.getBytes(), key.getBytes());
  47.                 outputEncrypted(encBytes);
  48.             } else if(op == Operation.Decrypt) {
  49.                 byte[] unencBytes = applySingleBitXor(parseEncrypted(str), key.getBytes());
  50.                 System.out.println(new String(unencBytes));
  51.             } else {
  52.                 throw new Exception("...the fuck?");
  53.             }
  54.  
  55.         } catch(Exception ex) {
  56.             System.out.println("This not a lesson in proper input validation and exception-handling... " + ex.getMessage());
  57.             ex.printStackTrace();
  58.             System.out.println("Usage: java LameSinglebitEncryption [Encrypt|Decrypt] key string-to-transform");
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement