1 19 package org.columba.core.base; 20 21 import java.io.UnsupportedEncodingException ; 22 import java.nio.ByteBuffer ; 23 import java.security.InvalidKeyException ; 24 import java.security.Key ; 25 import java.security.NoSuchAlgorithmException ; 26 import java.util.logging.Logger ; 27 28 import javax.crypto.BadPaddingException; 29 import javax.crypto.Cipher; 30 import javax.crypto.IllegalBlockSizeException; 31 import javax.crypto.NoSuchPaddingException; 32 import javax.crypto.spec.SecretKeySpec; 33 34 import org.columba.ristretto.coder.Base64; 35 36 public class Blowfish { 37 private static final Logger LOG = Logger 38 .getLogger("org.columba.util.blowfish"); 40 private static final byte[] BYTES = { -127, 88, 27, -88, -13, -56, 19, -4, 41 45, 25, 38, 70, -17, 40, 36, -23 }; 42 43 private static final Key KEY = new SecretKeySpec(BYTES, "Blowfish"); 45 public static String encrypt(char[] source) { 46 try { 47 Cipher blowCipher = Cipher.getInstance("Blowfish"); 50 blowCipher.init(Cipher.ENCRYPT_MODE, KEY); 52 53 byte[] cleartext = new String (source).getBytes("UTF-8"); 56 byte[] ciphertext = blowCipher.doFinal(cleartext); 58 59 return Base64.encode(ByteBuffer.wrap(ciphertext)).toString(); 61 } catch (InvalidKeyException e) { 62 LOG.severe(e.toString()); 63 } catch (NoSuchAlgorithmException e) { 64 LOG.severe(e.toString()); 65 } catch (NoSuchPaddingException e) { 66 LOG.severe(e.toString()); 67 } catch (UnsupportedEncodingException e) { 68 LOG.severe(e.toString()); 69 } catch (IllegalStateException e) { 70 LOG.severe(e.toString()); 71 } catch (IllegalBlockSizeException e) { 72 LOG.severe(e.toString()); 73 } catch (BadPaddingException e) { 74 LOG.severe(e.toString()); 75 } 76 77 return new String (); 78 } 79 80 public static char[] decrypt(String source) { 81 try { 82 Cipher blowCipher = Cipher.getInstance("Blowfish"); 85 blowCipher.init(Cipher.DECRYPT_MODE, KEY); 87 88 ByteBuffer ciphertext = Base64.decode(source); 90 byte[] cipherArray = new byte[ciphertext.limit()]; 91 ciphertext.get(cipherArray); 92 93 byte[] cleartext = blowCipher.doFinal(cipherArray); 95 96 return new String (cleartext, "UTF-8").toCharArray(); } catch (InvalidKeyException e) { 99 LOG.severe(e.toString()); 100 } catch (NoSuchAlgorithmException e) { 101 LOG.severe(e.toString()); 102 } catch (NoSuchPaddingException e) { 103 LOG.severe(e.toString()); 104 } catch (UnsupportedEncodingException e) { 105 LOG.severe(e.toString()); 106 } catch (IllegalStateException e) { 107 LOG.severe(e.toString()); 108 } catch (IllegalBlockSizeException e) { 109 LOG.severe(e.toString()); 110 } catch (BadPaddingException e) { 111 LOG.severe(e.toString()); 112 } 113 114 return new char[0]; 115 } 116 } | Popular Tags |