天天看點

java實作SM4的PKCS7Padding填充模式

最近在寫加解密的實作,從網上檢視SM4的pkcs7padding實作方式,原理有很多,但是用java實作的方法沒有找到,是以自己寫了一個分享出來,下篇是對填充後的還原方法。

    public static byte[] PKCS5Padding(byte[] inputByte) throws Exception {

        //判斷參數是否為空,為空抛出錯誤

        if (isEmpty(inputByte)) {

            throw new Exception("資料異常,PKCS5Padding填充模式錯誤,位元組參數為空!");

        }

        try {

            // 獲位元組長度

            int length = inputByte.length;

            // 補齊位數

            int leftLength = 16 - (length % 16 == 0 ? 16 : length % 16);

            // 定義新位元組

            byte[] arrayReturn = new byte[length + leftLength];

            // 定義填充位元組

            byte[] plusbyte = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,

                    0x0f };

            // 是否滿足為16位元組倍數

            if (leftLength > 0) {

                // 不滿足16倍數自動填充

                for (int i = 0; i < length + leftLength; i++) {

                    if (i < length) {

                        // 指派

                        arrayReturn[i] = inputByte[i];

                    } else {

                        // 補齊位數

                        arrayReturn[i] = plusbyte[leftLength];

                    }

                }

                // System.out.println("填充的位元組:"+plusbyte[leftLength]);

            } else {

                // 為16位元組倍數不需要補齊,直接傳回

                return inputByte;

            }

            return arrayReturn;

        } catch (Exception e) {

            throw new Exception("資料異常,PKCS5Padding填充模式錯誤,異常抛出!" + e.getMessage());

        }

    }