Java使用AES算法進行加密解密

1、加密算法

/**
     * 加密
     * @param src 源數據字節數組
     * @param key 密鑰字節數組
     * @return 加密後的字節數組
     */
    public static byte[] Encrypt(byte[] src, byte[] key) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");//"算法/模式/補碼方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        return cipher.doFinal(src);
    }

2、解密數組

/**
     * 解密
     * @param src 加密後的字節數據
     * @param key 密鑰字節數組
     * @return 加密後的字節數組
     * @throws Exception 異常
     */
    public static byte[] Decrypt(byte[] src, byte[] key) throws Exception {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            try {
                return cipher.doFinal(key);
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

3、hex字符串與字節數組互轉app

/**
     * 將二進制轉換成16進制字符串
     * @param buf 字節數組
     * @return 字符串
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 將16進制字符串轉換爲二進制
     * @param hexStr 字符串
     * @return 字節數組
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

注:因工做內容常與單片機進行數據傳輸,因此不能直接使用字符串進行加密解密,須要多進行一次hex字符串的轉換加密

由於上述加密解密使用的補碼模式是NoPadding,因此輸入的字節必須是128位對應的16個字節的倍數,若有須要能夠將補碼模式改成如下模式spa

相關文章
相關標籤/搜索