import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class Util {
/**
* 加密方法
* @param data:要加密的数据
* @param key:秘钥
* @return
* @throws Exception
*/
public static String encryption(String data,String key) 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("DES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey,paramSpec);
byte[] bytes = cipher.doFinal(data.getBytes());
String str=byte2HexString(bytes);
return str;
} catch (Exception e)
{
throw new Exception(e);
}
}
/**
* byte[]转换成字符串
* @param b
* @return
*/
static String byte2HexString(byte[] b)
{
StringBuffer sb = new StringBuffer();
int length = b.length;
for (int i = 0; i < length; i++) {
String stmp = Integer.toHexString(b[i]&0xff);
if(stmp.length() == 1)
sb.append("0"+stmp);
else
sb.append(stmp);
}
return sb.toString();
}
/**
* 解密方法
* @param data:要解密的数据
* @param key:秘钥
* @return
* @throws Exception
*/
public static String decryption(String data,String key) 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("DES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.DECRYPT_MODE, secretKey,paramSpec);
String str=new String(cipher.doFinal(String2Byte(data)));
return str;
} catch (Exception e)
{
throw new Exception(e);
}
}
/**
* 16进制转换成byte[]
* @param hexString
* @return
*/
static byte[] String2Byte(String hexString)
{
if(hexString.length() % 2 ==1)
return null;
byte[] ret = new byte[hexString.length()/2];
for (int i = 0; i < hexString.length(); i+=2) {
ret[i/2] = Integer.decode("0x"+hexString.substring(i,i+2)).byteValue();
}
return ret;
}
}
加密实例:
try {
String string="广州市";
String encryption = null;
encryption=Util.encryption(string, "abcdefghijk");
Log.i("加密后的字符串:",encryption);
String decryption=null;
decryption=Util.decryption(encryption, "abcdefghijk");
Log.i("解密后的字符串:", decryption);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
运行结果:
02-06 15:56:09.840: I/加密后的字符串:(20768): f9618e92794af394
02-06 15:56:09.850: I/解密后的字符串:(20768): 广州