Guest User

Untitled

a guest
Jul 22nd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. public class DesEncrypter {
  2. Cipher ecipher;
  3. Cipher dcipher;
  4.  
  5. // 8-byte Salt
  6. byte[] salt = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
  7. (byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03 };
  8.  
  9. // Iteration count
  10. int iterationCount = 19;
  11.  
  12. public DesEncrypter(String passPhrase) {
  13. try {
  14. // Create the key
  15. KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(),
  16. salt, iterationCount);
  17. SecretKey key = SecretKeyFactory
  18. .getInstance("PBEWithMD5AndDES")
  19. .generateSecret(keySpec);
  20. ecipher = Cipher.getInstance(key.getAlgorithm());
  21. dcipher = Cipher.getInstance(key.getAlgorithm());
  22.  
  23. // Prepare the parameter to the ciphers
  24. AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
  25. iterationCount);
  26.  
  27. // Create the ciphers
  28. ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
  29. dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
  30. } catch (Exception e) {
  31. throw new RuntimeException(e);
  32. }
  33. }
  34.  
  35. public String encrypt(String str) {
  36. try {
  37. // Encode the string into bytes using utf-8
  38. byte[] utf8 = str.getBytes("UTF8");
  39.  
  40. // Encrypt
  41. byte[] enc = ecipher.doFinal(utf8);
  42.  
  43. // Encode bytes to base64 to get a string
  44. return Base64.encodeBase64String(enc);
  45. } catch (Exception e) {
  46. throw new RuntimeException(e);
  47. }
  48. }
  49.  
  50. public String decrypt(String str) {
  51. try {
  52. // Decode base64 to get bytes
  53. byte[] dec = Base64.decodeBase64(str);
  54.  
  55. // Decrypt
  56. byte[] utf8 = dcipher.doFinal(dec);
  57.  
  58. // Decode using utf-8
  59. return new String(utf8, "UTF8");
  60. } catch (Exception e) {
  61. throw new RuntimeException(e);
  62. }
  63. }
  64. }
Add Comment
Please, Sign In to add comment