标签:
import java.util.UUID; // 均在android.jar中
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
String key = new String(""); // 键值
String iv = new String(""); // 向量
// 加密,其参数为要加密的数据
public static String Encrypt(String data) throws Exception
{
byte[] raw = key.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// 设定算法/模式/补码方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// 设定向量增加算法强度
IvParameterSpec paramter = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, paramter);
// 使用Base64进行二次加密
byte[] encrypted = cipher.doFinal(data.getBytes());
String encryptData = new String(Base64.encode(encrypted, Base64.DEFAULT));
// 防止数据加密后出现换行符(去除换行符)
String changeData = new String(encryptData.replaceAll("\r|\n",""));
return changeData;
}
// 解密,其参数是要解密的数据
public static String Decrypt(String data) throws Exception
{
byte[] raw = key.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// 设定算法/模式/补码方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// 设定向量增加算法强度
IvParameterSpec parameter = new IvParameterSpec(iv.getBytes());
// 使用Base64进行二次加密
cipher.init(Cipher.DECRYPT_MODE, skeySpec, parameter);
byte[] encrypted1 = Base64.decode(data, Base64.DEFAULT);
try {
byte[] original = cipher.doFinal(encrypted1);
String DecryptData = new String(original);
return DecryptData;
} catch (Exception e) {
System.out.println(e.toString());
return "";
}
}
一般情况下,如果解密后的数据存在中文,在android中习惯上会以UTF-8显示出来,假设是如此:
可参考: http://www.sharejs.com/codes/java/5422
// 将utf-8转换为中文
public static String GetAnsiMsg(String dataStr)
{
int index = 0;
StringBuffer buffer = new StringBuffer();
int li_len = dataStr.length();
while (index < li_len)
{
if (index >= li_len - 1 || !"\\u".equals(dataStr.substring(index, index + 2)))
{
buffer.append(dataStr.charAt(index));
index++;
continue;
}
String charStr = "";
charStr = dataStr.substring(index + 2, index + 6);
char letter = (char) Integer.parseInt(charStr, 16);
buffer.append(letter);
index += 6;
}
return buffer.toString();
}
标签:
原文地址:http://www.cnblogs.com/SkyflyBird/p/4925341.html