PageRenderTime 92ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/org.filho.util.blowfish/src/org/filho/util/blowfish/cipher/AbstractBlowfishCipher.java

https://gitlab.com/rwf/blowfish-hasher
Java | 51 lines | 29 code | 11 blank | 11 comment | 1 complexity | cc8d35363d76dcc525395a73d5b6a822 MD5 | raw file
  1. package org.filho.util.blowfish.cipher;
  2. import java.security.InvalidKeyException;
  3. import java.security.NoSuchAlgorithmException;
  4. import javax.crypto.Cipher;
  5. import javax.crypto.NoSuchPaddingException;
  6. import javax.crypto.spec.SecretKeySpec;
  7. import org.filho.util.blowfish.hasher.Mode;
  8. /**
  9. * Contains all the methods to manipulate the blowfish hashes.
  10. * @author Roberto Filho
  11. *
  12. */
  13. public abstract class AbstractBlowfishCipher {
  14. public Cipher getCipher(Mode mode, SecretKeySpec keySpec) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
  15. // Use blowfish with ECB and PKCS5 padding
  16. Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
  17. // Set mode
  18. cipher.init(mode.getCipherMode(), keySpec);
  19. return cipher;
  20. }
  21. public SecretKeySpec getKey(String key) {
  22. // Configuration
  23. byte[] keyBytes = key.getBytes();
  24. // Create new Blowfish cipher
  25. SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "Blowfish");
  26. return keySpec;
  27. }
  28. private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
  29. // Converts byte array to hex string
  30. // From: http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
  31. public static String bytesToHex(byte[] bytes) {
  32. char[] hexChars = new char[bytes.length * 2];
  33. for (int j = 0; j < bytes.length; j++) {
  34. int v = bytes[j] & 0xFF;
  35. hexChars[j * 2] = hexArray[v >>> 4];
  36. hexChars[j * 2 + 1] = hexArray[v & 0x0F];
  37. }
  38. return new String(hexChars);
  39. }
  40. }