天天看點

Android AES加密 ecb模式加密

Android AES加密 ==ecb模式加密

下面有兩套代碼都可以實作

第一套
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;

public class AESECB {

    // 加密
    public static String Encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            System.out.print("Key為空null");
            return null;
        }
        // 判斷Key是否為16位
        if (sKey.length() != 16) {
            System.out.print("Key長度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/補碼方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

//        return new Base64().encodeToString(encrypted);//此處使用BASE64做轉碼功能,同時能起到2次加密的作用。
        return Base64.encodeToString(encrypted, Base64.DEFAULT);
    }

    // 解密
    public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判斷Key是否正确
            if (sKey == null) {
                System.out.print("Key為空null");
                return null;
            }
            // 判斷Key是否為16位
            if (sKey.length() != 16) {
                System.out.print("Key長度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
//            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            byte[] encrypted1 = Base64.decode(sSrc.getBytes("UTF-8"), Base64.DEFAULT);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        /*
         * 此處使用AES-128-ECB加密模式,key需要為16位。
         */
        // 需要加密的字串
        String sKey = "key值key值key值";
        String cSrc = "Linsk123456_ecb模式";
        System.out.println(cSrc);
        // 加密
        String enString = AESECB.Encrypt(cSrc, sKey);
        System.out.println("加密後的字串是:" + enString);

        // 解密
        String DeString = AESECB.Decrypt(enString, sKey);
        System.out.println("解密後的字串是:" + DeString);
    }
}
           

執行代碼,生成字元串末尾帶"\n",需要替換掉

String sKey = "key值key值key值";
AESECB.Encrypt("待加密字元串", sKey).replaceAll("\r|\n", "")
           
第二套
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密解密工具
 *
 * @author huangxiaoguo
 */
public class AESUtils {

    public static String encrypt(String sSrc, String sKey){
        String rts = "";
        try {
            byte[] data = sSrc.getBytes("utf-8");
            byte[] key = sKey.getBytes("utf-8");
            byte[] encrypted = encrypt(data, key);
            rts = Base64.encodeToString(encrypted, Base64.DEFAULT);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return rts;
    }

    public static String decrypt(String sSrc, String sKey) {
        String rts = "";
        try {
            byte[] raw = sKey.getBytes("utf-8");
            byte[] encrypted1 = Base64.decode(sSrc.getBytes("UTF-8"), Base64.DEFAULT);
            byte[] original = decrypt(encrypted1, raw);
            rts = new String(original,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return rts;
    }

    /**
     * AES加密
     *
     * @param data
     *            将要加密的内容
     * @param key
     *            密鑰
     * @return 已經加密的内容
     */
    public static byte[] encrypt(byte[] data, byte[] key) {
        //不足16位元組,補齊内容為內插補點
        int len = 16 - data.length % 16;
        for (int i = 0; i < len; i++) {
            byte[] bytes = { (byte) len };
            data = ArrayUtils.concat(data, bytes);
        }
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[] {};
    }

    /**
     * AES解密
     *
     * @param data
     *            将要解密的内容
     * @param key
     *            密鑰
     * @return 已經解密的内容
     */
    public static byte[] decrypt(byte[] data, byte[] key) {
        data = ArrayUtils.noPadding(data, -1);
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decryptData = cipher.doFinal(data);
            int len = 2 + ByteUtils.byteToInt(decryptData[4]) + 3;
            return ArrayUtils.noPadding(decryptData, len);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[] {};
    }
}
           

ArrayUtils

/**
 * 數組工具 
 *  
 * @author huangxiaoguo
 */  
public class ArrayUtils {  

    /** 
     * 合并數組 
     *  
     * @param firstArray 
     *            第一個數組 
     * @param secondArray 
     *            第二個數組 
     * @return 合并後的數組 
     */  
    public static byte[] concat(byte[] firstArray, byte[] secondArray) {  
        if (firstArray == null || secondArray == null) {  
            return null;  
        }  
        byte[] bytes = new byte[firstArray.length + secondArray.length];  
        System.arraycopy(firstArray, 0, bytes, 0, firstArray.length);  
        System.arraycopy(secondArray, 0, bytes, firstArray.length,  
                secondArray.length);  
        return bytes;  
    }  

    /** 
     * 去除數組中的補齊 
     *  
     * @param paddingBytes 
     *            源數組 
     * @param dataLength 
     *            去除補齊後的資料長度 
     * @return 去除補齊後的數組 
     */  
    public static byte[] noPadding(byte[] paddingBytes, int dataLength) {  
        if (paddingBytes == null) {  
            return null;  
        }  

        byte[] noPaddingBytes = null;  
        if (dataLength > 0) {  
            if (paddingBytes.length > dataLength) {  
                noPaddingBytes = new byte[dataLength];  
                System.arraycopy(paddingBytes, 0, noPaddingBytes, 0, dataLength);  
            } else {  
                noPaddingBytes = paddingBytes;  
            }  
        } else {  
            int index = paddingIndex(paddingBytes);  
            if (index > 0) {  
                noPaddingBytes = new byte[index];  
                System.arraycopy(paddingBytes, 0, noPaddingBytes, 0, index);  
            }  
        }  

        return noPaddingBytes;  
    }  

    /** 
     * 擷取補齊的位置 
     *  
     * @param paddingBytes 
     *            源數組 
     * @return 補齊的位置 
     */  
    private static int paddingIndex(byte[] paddingBytes) {  
        for (int i = paddingBytes.length - 1; i >= 0; i--) {  
            if (paddingBytes[i] != 0) {  
                return i + 1;  
            }  
        }  
        return -1;  
    }  
}
           

ByteUtils

public class ByteUtils {
    public static int byteToInt(byte b) {
        return (b) & 0xff;
    }
}
           

執行代碼,生成字元串末尾帶"\n",需要替換掉

String sKey = "key值key值key值";
AESUtils.encrypt("待加密字元串", sKey).replaceAll("\r|\n", "")
           

參考

https://blog.csdn.net/dingweijson/article/details/84920045

https://blog.csdn.net/huangxiaoguo1/article/details/78043098

繼續閱讀