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 ; 10 import java.security.spec.KeySpec ; 11 import java.security.spec.AlgorithmParameterSpec ; 12 13 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 passPhrase) throws Exception { 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 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 { 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 encrypt(String str) throws Exception { 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 decrypt(String str) throws Exception { 53 byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); 54 byte[] utf8 = dcipher.doFinal(dec); 55 return new String (utf8, "UTF8"); 56 } 57 } 58 | Popular Tags |