java使用des加密解密示例分享
import java.security.key;
import java.security.securerandom;
import java.security.spec.algorithmparameterspec;
import javax.crypto.cipher;
import javax.crypto.secretkeyfactory;
import javax.crypto.spec.deskeyspec;
import javax.crypto.spec.ivparameterspec;
import org.apache.commons.logging.log;
import org.apache.commons.logging.logfactory;
public class des
{
public static final string algorithm_des = "des/cbc/pkcs5padding";
private static log log = logfactory.getlog(des.class);
/**
* des算法,加密
*
* @param data 待加密字符串
* @param key 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合base64编码使用
* @throws cryptexception 异常
*/
public static string encode(string key,string data) throws exception
{
return encode(key, data.getbytes());
}
/**
* des算法,加密
*
* @param data 待加密字符串
* @param key 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合base64编码使用
* @throws cryptexception 异常
*/
public static string encode(string key,byte[] data) throws exception
{
try
{
deskeyspec dks = new deskeyspec(key.getbytes());
secretkeyfactory keyfactory = secretkeyfactory.getinstance("des");
//key的长度不能够小于8位字节
key secretkey = keyfactory.generatesecret(dks);
cipher cipher = cipher.getinstance(algorithm_des);
ivparameterspec iv = new ivparameterspec("********".getbytes());
algorithmparameterspec paramspec = iv;
cipher.init(cipher.encrypt_mode, secretkey,paramspec);
byte[] bytes = cipher.dofinal(data);
return base64.encode(bytes);
} catch (exception e)
{
throw new exception(e);
}
}
/**
* des算法,解密
*
* @param data 待解密字符串
* @param key 解密私钥,长度不能够小于8位
* @return 解密后的字节数组
* @throws exception 异常
*/
public static byte[] decode(string key,byte[] data) throws exception
{
try
{
securerandom sr = new securerandom();
deskeyspec dks = new deskeyspec(key.getbytes());
secretkeyfactory keyfactory = secretkeyfactory.getinstance("des");
//key的长度不能够小于8位字节
key secretkey = keyfactory.generatesecret(dks);
cipher cipher = cipher.getinstance(algorithm_des);
ivparameterspec iv = new ivparameterspec("********".getbytes());
algorithmparameterspec paramspec = iv;
cipher.init(cipher.decrypt_mode, secretkey,paramspec);
return cipher.dofinal(data);
} catch (exception e)
{
// e.printstacktrace();
throw new exception(e);
}
}
/**
* 获取编码后的值
* @param key
* @param data
* @return
* @throws exception
* @throws exception
*/
public static string decodevalue(string key,string data) throws exception
{
byte[] datas;
string value = null;
datas = decode(key, base64.decode(data));
value = new string(datas);
if (value.equals("")){
throw new exception();
}
return value;
}
}
上一篇: Android程序开发之获取汉字的首字母