Android AES加密与解密

by Netfairy - 2018-11-30
package com.example.aes;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.util.Log;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("加密结果")
                .setMessage(byte2hex(encrypt(hex2byte("12345678123456781234567812345678"),hex2byte("010200383338373737f30d0000000000"))))
                .setPositiveButton("确定", null)
                .show();
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("解密结果")
                .setMessage(byte2hex(decrypt(hex2byte("12345678123456781234567812345678"),hex2byte("3095cec9459b09d89293dc34f43ba8cb"))))
                .setPositiveButton("确定", null)
                .show();
    }

    private static byte[] encrypt(byte[] key, byte[] src)
    {
        try
        {
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");  //获取加密器
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES")); //初始化
            byte[] encrypted = cipher.doFinal(src);
            return encrypted;
        }
        catch (Exception e)
        {
            Log.i("ERROR", "加密出错!");
            return null;
        }
    }


    private static byte[] decrypt(byte[] key, byte[] encryptedText)
    {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
            byte[] decrypted = cipher.doFinal(encryptedText);
            return decrypted;
        }
        catch (Exception e)
        {
            Log.i("ERROR", "解密出错!");
            return null;
        }
    }

    // /** 字节数组转成16进制字符串 **/
    private static String byte2hex(byte[] b) { // 一个字节的数,
        StringBuilder sb = new StringBuilder(b.length * 2);
        String tmp = "";
        for (byte aB : b) {
            // 整数转成十六进制表示
            tmp = (Integer.toHexString(aB & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // 转成大写
    }

    // /** 将16进制字符串转换成字节数组 **/
    private static byte[] hex2byte(String inputString) {
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        inputString = inputString.toLowerCase();
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = inputString.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }
}