Advertisement
Guest User

Untitled

a guest
May 24th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. import java.security.GeneralSecurityException;
  2.  
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.SecretKeySpec;
  5.  
  6. import util.B64;
  7.  
  8.  
  9. public class Crypt {
  10.  
  11. public static void main(String[] args) throws Exception {
  12.  
  13. // Receive Key
  14. String KEY = "57238004e784498bbc2f8bf984565090";
  15.  
  16. // Message
  17. String MSG = "HELLO WORLD";
  18.  
  19. // Example
  20. String encrypt = encrypt(MSG, KEY);
  21. String decrypt = decrypt(B64.dec(encrypt), B64.enc(KEY));
  22. }
  23.  
  24. public static String encrypt(String msg, String keyHexString) throws GeneralSecurityException {
  25. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  26. SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(keyHexString), "AES");
  27. cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
  28. byte[] encrypted = cipher.doFinal(msg.getBytes());
  29. return new String(B64.enc(byteArrayToHexString(encrypted)));
  30. }
  31.  
  32. public static String decrypt(String msg64String, String keyHex64String) throws Exception {
  33. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  34. SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(B64.dec(keyHex64String)), "AES");
  35. cipher.init(Cipher.DECRYPT_MODE, sks, cipher.getParameters());
  36. byte[] encrypted = cipher.doFinal(hexStringToByteArray(msg64String));
  37. return new String(encrypted);
  38. }
  39.  
  40. public static byte[] hexStringToByteArray(String s) {
  41. byte[] b = new byte[s.length() / 2];
  42. for (int i = 0; i < b.length; i++) {
  43. int index = i * 2;
  44. int v = Integer.parseInt(s.substring(index, index + 2), 16);
  45. b[i] = (byte) v;
  46. }
  47. return b;
  48. }
  49.  
  50. public static String byteArrayToHexString(byte[] b) {
  51. StringBuilder sb = new StringBuilder(b.length * 2);
  52. for (int i = 0; i < b.length; i++) {
  53. int v = b[i] & 0xff;
  54. if (v < 16) {
  55. sb.append('0');
  56. }
  57. sb.append(Integer.toHexString(v));
  58. }
  59. return sb.toString().toUpperCase();
  60. }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement