java AES密碼編譯演算法實現與長度不一致的問題

來源:互聯網
上載者:User

最近上傳資料到一政府部門的系統,AES加密始終跟那邊的調試軟體對不上。

幾經折騰,發現得到的加密結果始終比調試軟體的結果多32位。如:

 代碼如下 複製代碼

EC4B4C4BD6C3BA3957C1833C9613336D
EC4B4C4BD6C3BA3957C1833C9613336DBF6417F3751BDF3844F7F889FE79E218

未經處理資料長度需要為16的整倍數。
最後發現原因為演算法填充參數的影響:

 代碼如下 複製代碼
package com.grt.michael.network.communicate.server_zhujianbu;
 
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
/*******************************************************************************
 * AES加解密演算法
 * 
 * @author arix04
 * 
 */
 
public class AES {
 
    // 加密
    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();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        IvParameterSpec iv = new IvParameterSpec("0000000000123456".getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());
         
        System.out.println("TEXT = " + new String(encrypted));
        return byte2hex(encrypted);
    }
 
    // 解密
    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("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            IvParameterSpec iv = new IvParameterSpec("0000000000123456".getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = hex2byte(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
 
    public static byte[] hex2byte(String strhex) {
        if (strhex == null) {
            return null;
        }
        int l = strhex.length();
        if (l % 2 == 1) {
            return null;
        }
        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / 2; i++) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
                    16);
        }
        return b;
    }
 
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }
 
    public static void main(String[] args) throws Exception {
        /*
         * 加密用的Key 可以用26個字母和數字組成,最好不要用保留字元,雖然不會錯,至於怎麼裁決,個人看情況而定
         */
        String cKey = "0000000000123456";
        // 需要加密的字串
        String cSrc = "1111122222333334";
        System.out.println(cSrc);
        // 加密
        long lStart = System.currentTimeMillis();
        String enString = AES.Encrypt(cSrc, cKey);
        System.out.println("加密後的字串是:" + enString);
 
        long lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("加密耗時:" + lUseTime + "毫秒");
        // 解密
        lStart = System.currentTimeMillis();
        String DeString = AES.Decrypt(enString, cKey);
        System.out.println("解密後的字串是:" + DeString);
        lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("解密耗時:" + lUseTime + "毫秒");
    }
}

參考資料:

 代碼如下 複製代碼
演算法/模式/填充                    16位元組加密後資料長度         不滿16位元組加密後長度
AES/CBC/NoPadding             16                         不支援
AES/CBC/PKCS5Padding          32                         16
AES/CBC/ISO10126Padding       32                          16
AES/CFB/NoPadding             16                          未經處理資料長度
AES/CFB/PKCS5Padding          32                          16
AES/CFB/ISO10126Padding       32                          16
AES/ECB/NoPadding             16                          不支援
AES/ECB/PKCS5Padding          32                          16
AES/ECB/ISO10126Padding       32                          16
AES/OFB/NoPadding             16                          未經處理資料長度
AES/OFB/PKCS5Padding          32                          16
AES/OFB/ISO10126Padding       32                          16
AES/PCBC/NoPadding            16                          不支援
AES/PCBC/PKCS5Padding         32                          16
AES/PCBC/ISO10126Padding      32                          16

可以看到,在未經處理資料長度為16的整數倍時,假如未經處理資料長度等於16*n,則使用NoPadding時加密後資料長度等於16*n,其它情況下加密資料長度等於16*(n+1)。在不足16的整數倍的情況下,假如未經處理資料長度等於16*n+m[其中m小於16],除了NoPadding填充之外的任何方式,加密資料長度都等於16*(n+1);NoPadding填充情況下,CBC、ECB和PCBC三種模式是不支援的,CFB、OFB兩種模式下則加密資料長度等於未經處理資料長度。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.