1 25 29 package org.jresearch.gossip.util; 30 31 import java.io.IOException ; 32 import java.io.UnsupportedEncodingException ; 33 34 import sun.misc.BASE64Decoder; 35 import sun.misc.BASE64Encoder; 36 import Acme.Crypto.DesCipher; 37 38 42 public class DesEncrypter { 43 44 private DesCipher cipher; 45 46 private final static String LENGTH_SUFF = "@"; 47 48 private final static String ENCODING = "UTF8"; 49 50 53 public DesEncrypter(String passPhrase) { 54 cipher = new DesCipher(passPhrase.getBytes()); 55 } 56 57 63 public String encrypt(String str) throws UnsupportedEncodingException { 64 StringBuffer sb = new StringBuffer (str); 65 sb.append(LENGTH_SUFF); 66 str = sb.toString(); 67 int padlength = padlength(str); 68 byte[] inputBytes = new byte[padlength], cryptBytes = new byte[padlength]; System.arraycopy(str.getBytes(), 0, inputBytes, 0, 71 str.getBytes().length); 72 for (int i = 0; i < padlength; i += 8) { 73 cipher.encrypt(inputBytes, i, cryptBytes, i); 74 } 75 return new BASE64Encoder().encode(cryptBytes); 76 } 77 78 83 public String decrypt(String str) throws IOException { 84 byte[] inputBytes = new BASE64Decoder().decodeBuffer(str); byte[] clearBytes = new byte[inputBytes.length]; for (int i = 0; i < inputBytes.length; i += 8) { 89 cipher.decrypt(inputBytes, i, clearBytes, i); 90 } 91 String result = new String (clearBytes, ENCODING); 92 93 return result.substring(0, result.lastIndexOf(LENGTH_SUFF)); 94 } 95 96 99 private static int padlength(String s) throws UnsupportedEncodingException { 100 int len = s.getBytes(ENCODING).length; 101 int mod = len % 8; 102 return len + ((mod == 0) ? 0 : 8 - mod); 103 } 104 } | Popular Tags |