android 使用Aes加密数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zl406707/article/details/77369310
使用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);
 
 

猜你喜欢

转载自blog.csdn.net/zl406707/article/details/77369310