PageRenderTime 29ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/BlowfishKey.java

https://github.com/muness/blowfish_encryption_example
Java | 74 lines | 53 code | 21 blank | 0 comment | 0 complexity | 1be106d339ad0ccf3506ea794f150750 MD5 | raw file
  1. import javax.crypto.Cipher;
  2. import java.security.Key;
  3. import java.security.KeyStore;
  4. import java.security.PrivateKey;
  5. import java.security.Security;
  6. import javax.crypto.spec.SecretKeySpec;
  7. import java.security.PublicKey;
  8. import java.security.cert.CertificateFactory;
  9. import java.security.*;
  10. import javax.crypto.*;
  11. import javax.crypto.spec.*;
  12. import java.io.*;
  13. public class BlowfishKey {
  14. public static void main(String[] args) throws Exception {
  15. String encoded = encryptAndEncode("hello world!");
  16. System.out.println("Encoded: " + encoded);
  17. System.out.println(decodeAndDecrypt(encoded));
  18. }
  19. public static String encryptAndEncode(String plainText) throws Exception {
  20. byte[] encrypted = encrypt(plainText);
  21. String base64encoded = Base64.encodeBytes(encrypted);
  22. return java.net.URLEncoder.encode(base64encoded, "UTF-8");
  23. }
  24. public static byte[] encrypt(String plainText) throws Exception {
  25. Cipher cipher = Cipher.getInstance("Blowfish");
  26. cipher.init(Cipher.ENCRYPT_MODE, getKeySpec());
  27. return cipher.doFinal(plainText.getBytes());
  28. }
  29. public static String decodeAndDecrypt(String cipherText) throws Exception {
  30. String base64encoded = java.net.URLDecoder.decode(cipherText, "UTF-8");
  31. byte[] encrypted = Base64.decode(base64encoded);
  32. return decrypt(encrypted);
  33. }
  34. public static String decrypt(byte[] cipherText) throws Exception {
  35. Cipher cipher = Cipher.getInstance("Blowfish");
  36. cipher.init(Cipher.DECRYPT_MODE, getKeySpec());
  37. byte[] decrypted = cipher.doFinal(cipherText);
  38. return(new String(decrypted));
  39. }
  40. public static SecretKeySpec getKeySpec() throws Exception {
  41. byte[] raw = getKey();
  42. return (new SecretKeySpec(raw, "Blowfish"));
  43. }
  44. public static byte[] getKey() throws Exception {
  45. File key = new File("key");
  46. long length = key.length();
  47. final FileInputStream fis = new FileInputStream(key);
  48. byte[] bytes = new byte[(int)length];
  49. fis.read(bytes);
  50. fis.close();
  51. return bytes;
  52. }
  53. }