1 12 13 package org.openbravo.utils; 14 15 import javax.servlet.ServletException ; 16 import javax.crypto.*; 17 import javax.crypto.spec.*; 18 19 public class CryptoUtility { 20 private static Cipher s_cipher = null; 21 private static SecretKey s_key = null; 22 23 public CryptoUtility() { 24 } 25 26 public static void main(String argv[]) throws Exception { 27 System.out.println("Enter encryption password: "); 28 System.out.flush(); 29 String clave = argv[0]; 30 System.out.println("************* " + clave); 31 String strEnc = CryptoUtility.encrypt(clave); 32 System.out.println("ENCRIPTED TEXT: " + strEnc); 33 System.out.println("DECRIPTED TEXT: " + CryptoUtility.decrypt(strEnc)); 34 } 35 36 private static void initCipher() { 37 try { 38 s_key = new SecretKeySpec(new byte[] { 39 100, 25, 28, -122, -26, 94, -3, -72 40 }, "DES"); 41 s_cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); 42 } catch(Exception ex) { 43 ex.printStackTrace(); 44 } 45 } 46 47 public static String encrypt(String value) throws ServletException { 48 byte encString[]; 49 String clearText; 50 clearText = value; 51 if(clearText == null) clearText = ""; 52 if(s_cipher == null) initCipher(); 53 if(s_cipher == null) throw new ServletException ("CryptoUtility.encrypt() - Can't load cipher"); 54 try { 55 s_cipher.init(Cipher.ENCRYPT_MODE, s_key); 56 encString = s_cipher.doFinal(clearText.getBytes()); 57 } catch (Exception ex) { 58 ex.printStackTrace(); 59 throw new ServletException ("CryptoUtility.encrypt() - Can't init cipher"); 60 } 61 return new String (encString); 62 } 63 64 public static String decrypt(String value) throws ServletException { 65 if(value == null) return null; 66 if(value.length() == 0) return value; 67 if(s_cipher == null) initCipher(); 68 if(s_cipher == null || value == null || value.length() <= 0) throw new ServletException ("CryptoUtility.decrypt() - Can't load cipher"); 69 byte out[]; 70 try { 71 s_cipher.init(Cipher.DECRYPT_MODE, s_key); 72 out = s_cipher.doFinal(value.getBytes()); 73 } catch (Exception ex) { 74 ex.printStackTrace(); 75 throw new ServletException ("CryptoUtility.decrypt() - Can't init cipher"); 76 } 77 return new String (out); 78 } 79 } 80 | Popular Tags |