您的位置:首页 > 移动开发 > Android开发

android 使用Aes加密数据

2017-08-18 14:32 579 查看
使用AES加密   本文使用  "AES/CBC/PKCS5Padding"      CBC模式需用到两个公钥 加解密 工具类:
public class AES128utils {
//    public static final String AES128_KEY="kabuke1yc1881cn1";

/**
* 加密
* @param content
* @param key
* @return
*/
public static String jiaMi(String content, String key,String vi) {

try {
byte[] byteContent = content.getBytes("UTF-8");
// 注意,为了能与 iOS 统一
// 这里的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");

byte[] initParam = vi.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(byteContent);
String data=new BASE64Encoder().encode(encryptedBytes);
//URL转码    看后台规定    本文用到了 URL转码
String net= URLEncoder.encode(data,"UTF-8");
// 同样对加密后数据进行 base64 编码
return net;
} catch (Exception e) {
return null;
}
}

/**
* 解密
* @param content
* @param key
* @return
*/
public static String jieMi(String content, String key,String vi) {
try {
// base64 解码
byte[] encryptedBytes = new BASE64Decoder().decodeBuffer(content);
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = vi.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] result = cipher.doFinal(encryptedBytes);
return new String(result, "UTF-8");
} catch (Exception e) {
//e.printStackTrace();
return null;
}
}
}
Activity 内容调取加解密工具类
/**
* 加密
* @senddata content
* @param key
* @iv
*/
    String jiamidata=AES128utils.jiaMi(senddata,key,iv);//数据加密Log.d("zl","加密后上传的提交信息密文:"+jiamidata);
String jiemi = AES128utils.jieMi(newStr, key, iv);
    Log.d("zl","解密后上传的提交信息明文:"+jiamidata);

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: