/home/erning/tmp/webservice-test/server/src/sample/server/SampleServiceImpl.java

//-------------------------------------------------------------------------- 
// $Id$ 
//-------------------------------------------------------------------------- 
// Copyright (c) 1995-2005 Zhang Erning <zendragon@dragonsoft.net> 
// 
// The use and distribution terms for this software are covered by the 
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php) 
// which can be found in the file CPL.TXT at the root of this distribution. 
// By using this software in any fashion, you are agreeing to be bound by 
// the terms of this license. 
// 
// You must not remove this notice, or any other, from this software. 
//-------------------------------------------------------------------------- 
 
package sample.server; 
 
import org.apache.commons.codec.binary.Base64; 
import org.apache.commons.lang.StringUtils; 
 
import javax.crypto.KeyGenerator; 
import javax.crypto.SecretKey; 
import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec; 
 
import sample.SampleService; 
 
public class SampleServiceImpl implements SampleService 
{ 
    public static final char SPLITER = '|'; 
    public static final String ALGORITHM = "DES";
public String encrypt(String b64Data) throws Exception { SecretKey secretKey = KeyGenerator.getInstance(ALGORITHM).generateKey(); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] data = Base64.decodeBase64(b64Data.getBytes()); byte[] encryptedData = cipher.doFinal(data); String b64EncryptedData = new String(Base64.encodeBase64(encryptedData)); String b64SecretKey = new String(Base64.encodeBase64(secretKey.getEncoded())); String encrypted = b64EncryptedData + SPLITER + b64SecretKey; return encrypted; }
public String decrypt(String encrypted) throws Exception { String[] strs = StringUtils.split(encrypted, SPLITER); String b64EncryptedData = strs[0]; String b64SecretKey = strs[1]; SecretKey secretKey = new SecretKeySpec(Base64.decodeBase64(b64SecretKey.getBytes()), ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] encryptedData = Base64.decodeBase64(b64EncryptedData.getBytes()); byte[] data = cipher.doFinal(encryptedData); String b64Data = new String(Base64.encodeBase64(data)); return b64Data; } }