1 package org.myoodb.core; 25 26 import java.io.*; 27 import javax.crypto.*; 28 import javax.crypto.spec.*; 29 import java.security.spec.*; 30 31 public class Crypto 32 { 33 private static String m_passPhrase = null; 34 35 public static void setPassPhrase(String passPhrase) 36 { 37 m_passPhrase = passPhrase; 38 } 39 40 public static String getPassPhrase() 41 { 42 return m_passPhrase; 43 } 44 45 private Cipher m_ecipher; 46 private Cipher m_dcipher; 47 48 private byte[] m_salt = 49 { 50 (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32, 51 (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03 52 }; 53 54 private int m_iterationCount = 19; 55 56 public Crypto(String passPhrase) throws Exception 57 { 58 KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), m_salt, m_iterationCount); 59 SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); 60 m_ecipher = Cipher.getInstance(key.getAlgorithm()); 61 m_dcipher = Cipher.getInstance(key.getAlgorithm()); 62 63 AlgorithmParameterSpec paramSpec = new PBEParameterSpec(m_salt, m_iterationCount); 64 m_ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); 65 m_dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); 66 } 67 68 public String encrypt(String str) throws Exception 69 { 70 byte[] utf8 = str.getBytes("UTF8"); 71 byte[] enc = m_ecipher.doFinal(utf8); 72 return new sun.misc.BASE64Encoder().encode(enc); 73 } 74 75 public String decrypt(String str) throws Exception 76 { 77 byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); 78 byte[] utf8 = m_dcipher.doFinal(dec); 79 return new String (utf8, "UTF8"); 80 } 81 } 82 | Popular Tags |