package sample;
import java.security.*;
import javax.crypto.*;
/**//**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author George Hill
* @version 1.0
*/
public class Test {
// 加密使用的Key
private SecretKey key;
// 加密算法,JCE可用DES,DESede和Blowfish
private static final String algorithm = "DES";
public Test() throws NoSuchAlgorithmException {
KeyGenerator generator = KeyGenerator.getInstance(algorithm);
key = generator.generateKey();
}
/**//**
* 利用DES算法加密
* @param s String 需要加密的字符串
* @return String 加密后的字符串
* @throws Exception
*/
public String encryptData(String s) throws Exception {
Cipher c = Cipher.getInstance(algorithm);
c.init(Cipher.ENCRYPT_MODE, key);
return new String(c.doFinal(s.getBytes()));
}
/**//**
* 利用DES算法解密
* @param s String 需要解密的字符串
* @return String 解密后的字符串
* @throws Exception
*/
public String decryptData(String s) throws Exception {
Cipher c = Cipher.getInstance(algorithm);
c.init(Cipher.DECRYPT_MODE, key);
return new String(c.doFinal(s.getBytes()));
}
/**//**
* 测试程序
* @param args String[]
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String s = "Hello";
Test test = new Test();
String encrypt = test.encryptData(s);
System.out.println(encrypt);
String decrypt = test.decryptData(encrypt);
System.out.println(decrypt);
}
}