Advertisement
SVXX

XOR Strings

Aug 15th, 2012
659
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. package test.padencryption;
  2. import java.util.regex.*;
  3. import java.util.*;
  4.  
  5. public class StringEncrypt
  6. {
  7.     String s1, s2, result;
  8.     static boolean isValid(String test)
  9.     {
  10.         if(test.matches("([0-9A-F])+")) //Regex expression for hexadecimal number
  11.                 return true;
  12.         else
  13.                 return false;
  14.     }
  15.    
  16.     public String encrypt(String data, String pad)
  17.     {
  18.         int x1 = Integer.parseInt(data, 16); //Parse string into hex integer.
  19.         int x2 = Integer.parseInt(pad, 16);
  20.         int x3 = x1 ^ x2; //XORing
  21.         String res = String.format("%06x", x3); //Format string. Pad with 0s if required, min width 6.
  22.         res = res.replace('a', 'A');
  23.         res = res.replace('b', 'B');
  24.         res = res.replace('c', 'C');
  25.             res = res.replace('d', 'D');
  26.         res = res.replace('e', 'E');
  27.         res = res.replace('f', 'F');
  28.         return res;
  29.     }
  30.    
  31.     public static void main(String[] args)
  32.     {
  33.         Scanner input = new Scanner(System.in);
  34.         StringEncrypt obj = new StringEncrypt();
  35.         System.out.println("Enter the first string : ");
  36.         obj.s1 = input.next();
  37.         System.out.println("Enter the second string: ");
  38.         obj.s2 = input.next();
  39.                 //Check for validity. Strings must be equal length.
  40.         if((isValid(obj.s1)) && (isValid(obj.s2)) && (obj.s1.length() == obj.s2.length()))
  41.         {
  42.             obj.result = obj.encrypt(obj.s1, obj.s2);
  43.             System.out.println("The result is = " + obj.result);
  44.         }
  45.         else
  46.             System.out.println("Invalid entries");
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement