1 21 package oracle.toplink.essentials.internal.security; 23 24 import java.io.IOException ; 25 import java.io.ObjectInputStream ; 26 import java.io.ObjectOutputStream ; 27 import java.io.ByteArrayInputStream ; 28 import java.io.ByteArrayOutputStream ; 29 import javax.crypto.Cipher; 30 import javax.crypto.SecretKey; 31 import javax.crypto.spec.DESKeySpec; 32 import javax.crypto.SecretKeyFactory; 33 import javax.crypto.CipherInputStream; 34 import javax.crypto.CipherOutputStream; 35 import oracle.toplink.essentials.internal.helper.Helper; 36 import oracle.toplink.essentials.exceptions.ValidationException; 37 import oracle.toplink.essentials.exceptions.ConversionException; 38 39 44 public class JCEEncryptor implements Securable { 45 private Cipher m_cipher; 46 private final String m_algorithm = "DES"; 47 private final String m_padding = "DES/ECB/PKCS5Padding"; 48 49 public JCEEncryptor() throws Exception { 50 51 62 m_cipher = Cipher.getInstance(m_padding); 63 } 64 65 68 public synchronized String encryptPassword(String password) { 69 try { 70 m_cipher.init(Cipher.ENCRYPT_MODE, Synergizer.getMultitasker(m_algorithm)); 71 72 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 73 CipherOutputStream cos = new CipherOutputStream(baos, m_cipher); 74 ObjectOutputStream oos = new ObjectOutputStream (cos); 75 76 oos.writeObject(password); 77 oos.flush(); 78 oos.close(); 79 80 return Helper.buildHexStringFromBytes(baos.toByteArray()); 81 } catch (Exception e) { 82 throw ValidationException.errorEncryptingPassword(e); 83 } 84 } 85 86 90 public synchronized String decryptPassword(String encryptedPswd) { 91 String password = ""; 92 93 try { 94 m_cipher.init(Cipher.DECRYPT_MODE, Synergizer.getMultitasker(m_algorithm)); 95 96 byte[] bytePassword = Helper.buildBytesFromHexString(encryptedPswd); 97 98 ByteArrayInputStream bais = new ByteArrayInputStream (bytePassword); 99 CipherInputStream cis = new CipherInputStream(bais, m_cipher); 100 ObjectInputStream ois = new ObjectInputStream (cis); 101 102 password = (String )ois.readObject(); 103 ois.close(); 104 } catch (IOException e) { 105 password = encryptedPswd; 107 } catch (ArrayIndexOutOfBoundsException e) { 108 password = encryptedPswd; 110 } catch (ConversionException e) { 111 password = encryptedPswd; 113 } catch (Exception e) { 114 throw ValidationException.errorDecryptingPassword(e); 115 } 116 117 return password; 118 } 119 120 private static class Synergizer { 121 private static String multitasker = "E60B80C7AEC78038"; 122 123 static public SecretKey getMultitasker(String algorithm) throws Exception { 124 SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm); 125 return skf.generateSecret(new DESKeySpec(Helper.buildBytesFromHexString(multitasker))); 126 } 127 } 128 } 129 | Popular Tags |