KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > calipso > reportgenerator > common > Encrypter


1 package com.calipso.reportgenerator.common;
2
3 import javax.crypto.Cipher;
4 import javax.crypto.SecretKey;
5 import javax.crypto.IllegalBlockSizeException;
6 import javax.crypto.SecretKeyFactory;
7 import javax.crypto.spec.PBEKeySpec;
8 import javax.crypto.spec.PBEParameterSpec;
9 import java.io.UnsupportedEncodingException JavaDoc;
10 import java.security.spec.KeySpec JavaDoc;
11 import java.security.spec.AlgorithmParameterSpec JavaDoc;
12
13 /**
14  * User: jbassino
15  * Date: 31-ago-2005
16  * Time: 11:34:26
17  */

18 public class Encrypter {
19   private Cipher ecipher;
20   private Cipher dcipher;
21
22   private byte[] salt = {
23       (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
24       (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
25   };
26
27   private int iterationCount = 19;
28
29   public Encrypter(String JavaDoc passPhrase) throws Exception JavaDoc{
30     KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
31     SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
32     ecipher = Cipher.getInstance(key.getAlgorithm());
33     dcipher = Cipher.getInstance(key.getAlgorithm());
34     AlgorithmParameterSpec JavaDoc paramSpec = new PBEParameterSpec(salt, iterationCount);
35     ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
36     dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
37   }
38
39   public Encrypter(SecretKey key) throws Exception JavaDoc{
40     ecipher = Cipher.getInstance("DESese");
41     dcipher = Cipher.getInstance("DESese");
42     ecipher.init(Cipher.ENCRYPT_MODE, key);
43     dcipher.init(Cipher.DECRYPT_MODE, key);
44   }
45
46   public String JavaDoc encrypt(String JavaDoc str) throws Exception JavaDoc{
47     byte[] utf8 = str.getBytes("UTF8");
48     byte[] enc = ecipher.doFinal(utf8);
49     return new sun.misc.BASE64Encoder().encode(enc);
50   }
51
52   public String JavaDoc decrypt(String JavaDoc str) throws Exception JavaDoc{
53     byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
54     byte[] utf8 = dcipher.doFinal(dec);
55     return new String JavaDoc(utf8, "UTF8");
56   }
57 }
58
Popular Tags