1 19 package org.lucane.common.crypto; 20 21 import javax.crypto.*; 22 import javax.crypto.spec.*; 23 import sun.misc.*; 24 25 public class BlowFish 26 { 27 public static String cipher(String key, String str) 28 throws CryptoException 29 { 30 if(key.length() > 16) 31 key = key.substring(0, 16); 32 33 SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "BlowFish"); 34 Cipher cipher; 35 byte[] encrypted; 36 37 try { 38 cipher = Cipher.getInstance("BlowFish"); 39 cipher.init(Cipher.ENCRYPT_MODE, secretKey); 40 encrypted = cipher.doFinal(str.getBytes()); 41 } catch(Exception e) { 42 throw new CryptoException(e); 43 } 44 45 return new BASE64Encoder().encode(encrypted); 46 } 47 48 public static String decipher(String key, String str) 49 throws CryptoException 50 { 51 if(key.length() > 16) 52 key = key.substring(0, 16); 53 54 SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "BlowFish"); 55 Cipher cipher; 56 byte[] decrypted; 57 58 try { 59 cipher = Cipher.getInstance("BlowFish"); 60 cipher.init(Cipher.DECRYPT_MODE, secretKey); 61 decrypted = cipher.doFinal(new BASE64Decoder().decodeBuffer(str)); 62 } catch(Exception e) { 63 throw new CryptoException(e); 64 } 65 66 return new String (decrypted); 67 } 68 69 public static void main(String [] args) 70 throws Exception 71 { 72 System.out.println(cipher("guest", "str")); 73 } 74 } | Popular Tags |