android 使用des算法
转自:http://www.linuxidc.com/Linux/2011-08/41866.htm 稍有改动
import java.security.Key;import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
importjavax.crypto.SecretKeyFactory;
importjavax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;import android.util.Base64;
public class DesUtils { public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";
/**
*DES算法,加密
*@paramdata待加密字符串
*@paramkey加密私钥,长度不能够小于8位
*@return加密后的字节数组,一般结合Base64编码使用
*@throwsCryptException异常
*/
publicstaticStringencode(Stringkey,Stringdata)throwsException{
returnencode(key,data.getBytes());
}/**
*DES算法,加密
*@paramdata待加密字符串
*@paramkey加密私钥,长度不能够小于8位
*@return加密后的字节数组,一般结合Base64编码使用
*@throwsCryptException
*异常
*/
privatestaticStringencode(Stringkey,byte[]data)throwsException{
try{
DESKeySpecdks=newDESKeySpec(key.getBytes());
SecretKeyFactorykeyFactory=SecretKeyFactory.getInstance("DES");
//key的长度不能够小于8位字节
KeysecretKey=keyFactory.generateSecret(dks);
Ciphercipher=Cipher.getInstance(ALGORITHM_DES);
IvParameterSpeciv=newIvParameterSpec("12345678".getBytes());
AlgorithmParameterSpecparamSpec=iv;
cipher.init(Cipher.ENCRYPT_MODE,secretKey,paramSpec);
byte[]bytes=cipher.doFinal(data);
returnBase64.encodeToString(bytes,0);
}catch(Exceptione){
thrownewException(e);
}
}/**
*DES算法,解密
*@paramdata待解密字符串
*@paramkey解密私钥,长度不能够小于8位
*@return解密后的字节数组
*@throwsException异常
*/
privatestaticbyte[]decode(Stringkey,byte[]data)throwsException{
try{
DESKeySpecdks=newDESKeySpec(key.getBytes());
SecretKeyFactorykeyFactory=SecretKeyFactory.getInstance("DES");
//key的长度不能够小于8位字节
KeysecretKey=keyFactory.generateSecret(dks);
Ciphercipher=Cipher.getInstance(ALGORITHM_DES);
IvParameterSpeciv=newIvParameterSpec("12345678".getBytes());
AlgorithmParameterSpecparamSpec=iv;
cipher.init(Cipher.DECRYPT_MODE,secretKey,paramSpec);
returncipher.doFinal(data);
}catch(Exceptione){
thrownewException(e);
}
}
/**
*解密.
*@paramkey
*@paramdata
*@return
*@throwsException
*/
publicstaticStringdecode(Stringkey,Stringdata){
byte[]datas;
Stringvalue=null;
try{
if(System.getProperty("os.name")!=null
&&(System.getProperty("os.name").equalsIgnoreCase("sunos")||System
.getProperty("os.name").equalsIgnoreCase("linux"))){
datas=decode(key,Base64.decode(data,0));
}else{
datas=decode(key,Base64.decode(data,0));
}value = new String(datas);
}catch(Exceptione){
value="";
}
returnvalue;
}}