01: package com.calipso.reportgenerator.common;
02:
03: import javax.crypto.Cipher;
04: import javax.crypto.SecretKey;
05: import javax.crypto.IllegalBlockSizeException;
06: import javax.crypto.SecretKeyFactory;
07: import javax.crypto.spec.PBEKeySpec;
08: import javax.crypto.spec.PBEParameterSpec;
09: import java.io.UnsupportedEncodingException;
10: import java.security.spec.KeySpec;
11: import java.security.spec.AlgorithmParameterSpec;
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 = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8,
23: (byte) 0x32, (byte) 0x56, (byte) 0x35, (byte) 0xE3,
24: (byte) 0x03 };
25:
26: private int iterationCount = 19;
27:
28: public Encrypter(String passPhrase) throws Exception {
29: KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(),
30: salt, iterationCount);
31: SecretKey key = SecretKeyFactory
32: .getInstance("PBEWithMD5AndDES")
33: .generateSecret(keySpec);
34: ecipher = Cipher.getInstance(key.getAlgorithm());
35: dcipher = Cipher.getInstance(key.getAlgorithm());
36: AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
37: iterationCount);
38: ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
39: dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
40: }
41:
42: public Encrypter(SecretKey key) throws Exception {
43: ecipher = Cipher.getInstance("DESese");
44: dcipher = Cipher.getInstance("DESese");
45: ecipher.init(Cipher.ENCRYPT_MODE, key);
46: dcipher.init(Cipher.DECRYPT_MODE, key);
47: }
48:
49: public String encrypt(String str) throws Exception {
50: byte[] utf8 = str.getBytes("UTF8");
51: byte[] enc = ecipher.doFinal(utf8);
52: return new sun.misc.BASE64Encoder().encode(enc);
53: }
54:
55: public String decrypt(String str) throws Exception {
56: byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
57: byte[] utf8 = dcipher.doFinal(dec);
58: return new String(utf8, "UTF8");
59: }
60: }
|