KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lucane > common > crypto > BlowFish


1 /*
2  * Lucane - a collaborative platform
3  * Copyright (C) 2004 Vincent Fiack <vfiack@mail15.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */

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 JavaDoc cipher(String JavaDoc key, String JavaDoc 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 JavaDoc e) {
42             throw new CryptoException(e);
43         }
44
45         return new BASE64Encoder().encode(encrypted);
46     }
47
48     public static String JavaDoc decipher(String JavaDoc key, String JavaDoc 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 JavaDoc e) {
63             throw new CryptoException(e);
64         }
65         
66         return new String JavaDoc(decrypted);
67     }
68     
69     public static void main(String JavaDoc [] args)
70     throws Exception JavaDoc
71     {
72         System.out.println(cipher("guest", "str"));
73     }
74 }
Popular Tags