Android实现CBC加解密

Android实现CBC加解密

  • 前言
  • 导入bcprov.jar
  • AESCBCUtil.java
  • MainActivity.java
  • 运行结果

前言

CBC(Cipher-block chaining),即密码分组链接,是一种较为常用的加密模式。接下来介绍一下Android中实现CBC加解密的具体流程。

导入bcprov.jar

实现CBC加密需要用到bcprov.jar,百度网盘下载地址:
链接:https://pan.baidu.com/s/11l9HybOcizxzdaea2iiECQ
提取码:ijmz

AESCBCUtil.java

定义一个工具类AESCBCUtil,实现CBC加密、解密等方法:

package com.example.cbc;

import java.util.Locale;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.util.encoders.Base64;

public class AESCBCUtil {
    //密码
    private static final String key = "aaaabbbbccccdddd";
    //iv偏移量
    private static final String iv = "0000000000000000";

    /**
     * 加密:对字符串进行加密,并返回十六进制字符串(hex)
     *
     * @param encryptStr 需要加密的字符串
     * @return 加密后的十六进制字符串(hex)
     */
    public static String encrypt(String encryptStr,String key,String iv) {
        try {
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

            byte[] encrypted = cipher.doFinal(encryptStr.getBytes());
            byte[] encode = Base64.encode(encrypted);

            String string = new String(encode);
            return string;
            //     return byte2HexStr(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    /**
     * 解密:对加密后的十六进制字符串(hex)进行解密,并返回字符串
     *
     * @param encryptedStr 需要解密的,加密后的十六进制字符串
     * @return 解密后的字符串
     */
    public static String decrypt(String encryptedStr,String key,String iv) {
        try {
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);

            byte[] decode = Base64.decode(encryptedStr);

            //  byte[] bytes = hexStr2Bytes(encryptedStr);
            byte[] original = cipher.doFinal(decode);

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    /**
     * 十六进制字符串转换为byte[]
     *
     * @param hexStr 需要转换为byte[]的字符串
     * @return 转换后的byte[]
     */
    public static byte[] hexStr2Bytes(String hexStr) {

        /*对输入值进行规范化整理*/
        hexStr = hexStr.trim().replace(" ", "").toUpperCase(Locale.US);
        //处理值初始化
        int m = 0, n = 0;
        int iLen = hexStr.length() / 2; //计算长度
        byte[] ret = new byte[iLen]; //分配存储空间

        for (int i = 0; i < iLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            ret[i] = (byte) (Integer.decode("0x" + hexStr.substring(i * 2, m) + hexStr.substring(m, n)) & 0xFF);
        }
        return ret;
    }

    /**
     * byte[]转换为十六进制字符串
     *
     * @param bytes 需要转换为字符串的byte[]
     * @return 转换后的十六进制字符串
     */
    public static String byte2HexStr(byte[] bytes) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < bytes.length; n++) {
            stmp = (Integer.toHexString(bytes[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs;
    }

}

MainActivity.java

MainActivity.java中调用工具类AESCBCUtil的方法,进行测试数据的加解密:

package com.example.cbc;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private String key = "aaaabbbbccccdddd";//密钥,必须16位
    private String content1 = "fgsrgreatrt";//待加密内容
    private String content2 = "AyKRIVDV9PSQ9gOJLQG/bw==";//待解密内容
    private String iv = "0000000000000000";//偏移量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Jason", "encode result:" + AESCBCUtil.encrypt(content1, key, iv));
        Log.d("Jason", "decode result:" + AESCBCUtil.decrypt(content2, key, iv));
    }
}

运行结果

在安卓模拟器或真机上运行实现的程序,运行结果如下,成功完成了CBC加解密:
Android实现CBC加解密_第1张图片

你可能感兴趣的:(Android)