Java版SMS4加密解密算法

每個成功人士的背後,一定曾經作出過勇敢而又孤獨的決定。java

放棄不難,但堅持很酷~web

前言算法

最近工做中須要實現HBase自定義擴展sms4加密,今天就先來講一下Java版的SMS4加密解密算法的具體實現。微信

1、概述

1.1 基本概念

本算法是一個分組算法,由加解密算法和密鑰擴展算法組成。該算法的分組長度爲128比特(Bit),密鑰長度爲128比特(Bit),也就是16個字節(Bytes)。加密算法與密鑰擴展算法都採用32輪非線性迭代結構。解密算法與加密算法的結構相同,只是輪密鑰的使用順序相反,解密輪密鑰是加密輪密鑰的逆序。在SMS4的基礎類中,你會看到加密和解密的基礎函數是同一個(本篇文章中的sms4KeyExt()方法),只是須要一個int型的標誌位來判斷是加密仍是解密。app

1.2 密碼算法結構

  • 基本輪函數加迭代函數

  • 解密算法與加密算法相同學習

1.3 S盒:S-box

S 盒爲固定的8比特(Bit)輸入8比特(Bit)輸出的置換,記爲Sbox(⋅) 。測試

1.4 SMS4密碼算法

1.4.1 基本運算
  • ⨁        32比特異或大數據

  • ⋘ i     32比特循環左移i位flex

1.4.2 基本密碼部件
  • 非線性字節變換部件S盒

  • 非線性字變換τ:32位字的非線性變換

  • 字線性部件L變換

  • 字合成變換T

1.4.3 輪函數F

1.5 密鑰擴展算法

  • 常數FK

  • 固定參數CK

更多詳細的資料請私信 「SMS4」 到本公衆號,獲取SMS4相關資料(一個PPT,一個PDF)。

2、編碼實現

如下代碼可能與網上有些雷同,畢竟萬變不離其宗,但我將每個方法表明什麼意思,都寫了很詳細的註釋供你們理解,這樣能夠縮短你的學習時長。都快被本身感動哭了😭

package com.xxx.sms4;

import java.util.Arrays;

/**
 * @author CREATE_17
 * @description: SMS4加密與解密算法實現
 * @date: 2019/4/2 14:10
 */

public class Sms4 {

    /**
     * @description: ENCRYPT與DECRYPT爲加解密的判斷依據
     */

    private static final int ENCRYPT = 1;
    private static final int DECRYPT = 0;
    /**
     * @description: 輪數,輪函數的迭代次數
     * 加密算法與密鑰擴展算法都採用32輪非線性迭代結構。
     */

    private static final int ROUND = 32;
    private static final int BLOCK = 16;

    /**
     * @description: S盒中數據均採用16進製表示
     */

    private static short[] sBox = {
            0xd60x900xe90xfe0xcc0xe10x3d0xb70x160xb60x140xc20x280xfb0x2c0x05,
            0x2b0x670x9a0x760x2a0xbe0x040xc30xaa0x440x130x260x490x860x060x99,
            0x9c0x420x500xf40x910xef0x980x7a0x330x540x0b0x430xed0xcf0xac0x62,
            0xe40xb30x1c0xa90xc90x080xe80x950x800xdf0x940xfa0x750x8f0x3f0xa6,
            0x470x070xa70xfc0xf30x730x170xba0x830x590x3c0x190xe60x850x4f0xa8,
            0x680x6b0x810xb20x710x640xda0x8b0xf80xeb0x0f0x4b0x700x560x9d0x35,
            0x1e0x240x0e0x5e0x630x580xd10xa20x250x220x7c0x3b0x010x210x780x87,
            0xd40x000x460x570x9f0xd30x270x520x4c0x360x020xe70xa00xc40xc80x9e,
            0xea0xbf0x8a0xd20x400xc70x380xb50xa30xf70xf20xce0xf90x610x150xa1,
            0xe00xae0x5d0xa40x9b0x340x1a0x550xad0x930x320x300xf50x8c0xb10xe3,
            0x1d0xf60xe20x2e0x820x660xca0x600xc00x290x230xab0x0d0x530x4e0x6f,
            0xd50xdb0x370x450xde0xfd0x8e0x2f0x030xff0x6a0x720x6d0x6c0x5b0x51,
            0x8d0x1b0xaf0x920xbb0xdd0xbc0x7f0x110xd90x5c0x410x1f0x100x5a0xd8,
            0x0a0xc10x310x880xa50xcd0x7b0xbd0x2d0x740xd00x120xb80xe50xb40xb0,
            0x890x690x970x4a0x0c0x960x770x7e0x650xb90xf10x090xc50x6e0xc60x84,
            0x180xf00x7d0xec0x3a0xdc0x4d0x200x790xee0x5f0x3e0xd70xcb0x390x48
    };

    /**
     * @description: 常數FK,在密鑰擴展中使用一些常數
     */

    private static int[] fk = {0xa3b1bac60x56aa33500x677d91970xb27022dc};

    /**
     * @description: 32個固定參數CK
     * 產生規則:Ckij= (4i+j)×7(mod 256) ,i=0,1,2…31,j=0,1,…3
     */

    private static int[] ck = {
            0x00070e150x1c232a310x383f464d0x545b6269,
            0x70777e850x8c939aa10xa8afb6bd0xc4cbd2d9,
            0xe0e7eef50xfc030a110x181f262d0x343b4249,
            0x50575e650x6c737a810x888f969d0xa4abb2b9,
            0xc0c7ced50xdce3eaf10xf8ff060d0x141b2229,
            0x30373e450x4c535a610x686f767d0x848b9299,
            0xa0a7aeb50xbcc3cad10xd8dfe6ed0xf4fb0209,
            0x10171e250x2c333a410x484f565d0x646b7279
    };

    /**
     * @description: 移位,rot1(x,y)爲循環左移位y
     * @param: x
     * @param: y
     * @return: int
     */

    private int rotl(int x, int y) {
        return x << y | x >>> (32 - y);
    }

    /**
     * @description: 加解密,非線性τ函數:B=τ(A)
     * @param: a
     * @return: int
     */

    private int byteSub(int a) {
        return (sBox[a >>> 24 & 0xFF] & 0xFF) << 24
                ^ (sBox[a >>> 16 & 0xFF] & 0xFF) << 16
                ^ (sBox[a >>> 8 & 0xFF] & 0xFF) << 8
                ^ (sBox[a & 0xFF] & 0xFF);
    }

    /**
     * @description: 加解密的L函數
     * @param: b
     * @return: int
     */

    private int l1(int b) {
        return b ^ rotl(b, 2) ^ rotl(b, 10) ^ rotl(b, 18) ^ rotl(b, 24);
    }

    /**
     * @description: 密鑰擴展
     * @param: b
     * @return: int
     */

    private int l2(int b) {
        return b ^ rotl(b, 13) ^ rotl(b, 23);
    }

    /**
     * @description: SMS4的加密方法實現
     * @param: input(待輸入的明文)
     * @param: output(待輸出的密文)
     * @param: rk(輪密鑰)
     * @return: void
     */

    private void sms4Crypt(byte[] input, byte[] output, int[] rk) {
        int mid;
        int[] x = new int[4];
        int[] tmp = new int[4];
        for (int i = 0; i < 4; i++) {
            tmp[0] = input[4 * i] & 0xff;
            tmp[1] = input[1 + 4 * i] & 0xff;
            tmp[2] = input[2 + 4 * i] & 0xff;
            tmp[3] = input[3 + 4 * i] & 0xff;
            x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3];
        }
        // 進行32輪的加密變換操做
        for (int r = 0; r < 32; r += 4) {
            mid = x[1] ^ x[2] ^ x[3] ^ rk[r];
            mid = byteSub(mid);
            // x4
            x[0] = x[0] ^ l1(mid);

            mid = x[2] ^ x[3] ^ x[0] ^ rk[r + 1];
            mid = byteSub(mid);
            // x5
            x[1] = x[1] ^ l1(mid);

            mid = x[3] ^ x[0] ^ x[1] ^ rk[r + 2];
            mid = byteSub(mid);
            // x6
            x[2] = x[2] ^ l1(mid);

            mid = x[0] ^ x[1] ^ x[2] ^ rk[r + 3];
            mid = byteSub(mid);
            // x7
            x[3] = x[3] ^ l1(mid);
        }

        // 反序變換
        for (int j = 0; j < 16; j += 4) {
            output[j] = (byte) (x[3 - j / 4] >>> 24 & 0xFF);
            output[j + 1] = (byte) (x[3 - j / 4] >>> 16 & 0xFF);
            output[j + 2] = (byte) (x[3 - j / 4] >>> 8 & 0xFF);
            output[j + 3] = (byte) (x[3 - j / 4] & 0xFF);
        }
    }

    /**
     * @description: SMS4的密鑰擴展算法
     * @param: key(加密密鑰)
     * @param: rk(子密鑰)
     * @param: cryptFlag(加解密標誌)
     * @return: void
     */

    private void sms4KeyExt(byte[] key, int[] rk, int cryptFlag) {
        int r, mid;
        int[] x = new int[4];
        int[] tmp = new int[4];
        for (int i = 0; i < 4; i++) {
            // 實現對初始密鑰的分組(分爲4組)
            tmp[0] = key[4 * i] & 0xFF;
            tmp[1] = key[1 + 4 * i] & 0xff;
            tmp[2] = key[2 + 4 * i] & 0xff;
            tmp[3] = key[3 + 4 * i] & 0xff;

            x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3];
            x[i] = key[4 * i] << 24 | key[1 + 4 * i] << 16 | key[2 + 4 * i] << 8 | key[3 + 4 * i];
        }
        // 異或運算以後的結果
        x[0] ^= fk[0];
        x[1] ^= fk[1];
        x[2] ^= fk[2];
        x[3] ^= fk[3];
        for (r = 0; r < 32; r += 4) {
            //
            mid = x[1] ^ x[2] ^ x[3] ^ ck[r];
            mid = byteSub(mid);
            // rk0=K4
            rk[r] = x[0] ^= l2(mid);

            mid = x[2] ^ x[3] ^ x[0] ^ ck[r + 1];
            mid = byteSub(mid);
            // rk1=K5
            rk[r + 1] = x[1] ^= l2(mid);

            mid = x[3] ^ x[0] ^ x[1] ^ ck[r + 2];
            mid = byteSub(mid);
            // rk2=K6
            rk[r + 2] = x[2] ^= l2(mid);

            mid = x[0] ^ x[1] ^ x[2] ^ ck[r + 3];
            mid = byteSub(mid);
            // rk3=K7
            rk[r + 3] = x[3] ^= l2(mid);
        }

        // cryptFla==0 爲解密,解密時輪密鑰使用順序:rk31,rk30,...,rk0(逆序)
        if (cryptFlag == DECRYPT) {
            for (r = 0; r < 16; r++) {
                mid = rk[r];
                rk[r] = rk[31 - r];
                rk[31 - r] = mid;
            }
        }
    }

    /**
     * @description: 加解密的基礎方法
     * @param: in(待輸入的明文或密文)
     * @param: inLen(16)
     * @param: key(密鑰)
     * @param: out(待輸出的密文或明文)
     * @param: cryptFlag(加解密的判斷條件)
     * @return: int
     */

    private void sms4(byte[] in, int inLen, byte[] key, byte[] out, int cryptFlag) {
        int point = 0;
        int[] roundKey = new int[ROUND];
        sms4KeyExt(key, roundKey, cryptFlag);
        byte[] input;
        byte[] output = new byte[16];
        while (inLen >= BLOCK) {
            input = Arrays.copyOfRange(in, point, point + 16);
            sms4Crypt(input, output, roundKey);
            System.arraycopy(output, 0, out, point, BLOCK);
            inLen -= BLOCK;
            point += BLOCK;
        }
    }

    /**
     * @description: 明文加密
     * @param: plaintext(明文)
     * @param: key(密鑰)
     * @return: byte[]
     */

    private static byte[] encodeSMS4(String plaintext, byte[] key) {
        if (plaintext == null || "".equals(plaintext)) {
            return null;
        }
        for (int i = plaintext.getBytes().length % 16; i < 16; i++) {
            plaintext += '\0';
        }
        return Sms4.encodeSMS4(plaintext.getBytes(), key);
    }

    /**
     * @description: 不限明文長度的SMS4加密
     * @param: plainText(明文)
     * @param: key(密鑰)
     * @return: byte類型的明文加密結果
     */

    private static byte[] encodeSMS4(byte[] plainText, byte[] key) {
        byte[] ciphertext = new byte[plainText.length];
        int k = 0;
        int plainLen = plainText.length;
        while (k + 16 <= plainLen) {
            byte[] cellPlain = new byte[16];
            for (int i = 0; i < 16; i++) {
                cellPlain[i] = plainText[k + i];
            }
            byte[] cellCipher = encode16(cellPlain, key);
            for (int i = 0; i < cellCipher.length; i++) {
                ciphertext[k + i] = cellCipher[i];
            }
            k += 16;
        }
        return ciphertext;
    }

    /**
     * @description: 不限密文長度的SMS4解密,得到byte類型的明文
     * @param: cipherText(密文)
     * @param: key(密鑰)
     * @return: byte[]
     */

    private static byte[] decodeSMS4(byte[] cipherText, byte[] key) {
        byte[] plaintext = new byte[cipherText.length];
        int k = 0;
        int cipherLen = cipherText.length;
        while (k + 16 <= cipherLen) {
            byte[] cellCipher = new byte[16];
            for (int i = 0; i < 16; i++) {
                cellCipher[i] = cipherText[k + i];
            }
            byte[] cellPlain = decode16(cellCipher, key);
            for (int i = 0; i < cellPlain.length; i++) {
                plaintext[k + i] = cellPlain[i];
            }
            k += 16;
        }
        return plaintext;
    }

    /**
     * @description: 解密,得到明文字符串
     * @param: cipherText(密文)
     * @param: key(密鑰)
     * @return: java.lang.String
     */

    private static String decodeSMS4toString(byte[] cipherText, byte[] key) {
        byte[] plaintext = new byte[cipherText.length];
        plaintext = decodeSMS4(cipherText, key);
        return new String(plaintext);
    }

    /**
     * @description: 16位明文加密,獲得密文
     * @param: plainText(明文)
     * @param: key(密鑰)
     * @return: byte[]
     */

    private static byte[] encode16(byte[] plainText, byte[] key) {
        byte[] cipher = new byte[16];
        Sms4 sm4 = new Sms4();
        sm4.sms4(plainText, 16, key, cipher, ENCRYPT);
        return cipher;
    }

    /**
     * @description: 解密密文,返回字節類型的明文
     * @param: key
     * @return: byte[]
     */

    private static byte[] decode16(byte[] ciphertext, byte[] key) {
        byte[] plain = new byte[16];
        Sms4 sm4 = new Sms4();
        sm4.sms4(ciphertext, 16, key, plain, DECRYPT);
        return plain;
    }

    /**
     * @description: 將16進制byte類型的密文轉換爲String字符串
     * @param: byteArray
     * @return: java.lang.String
     */

    private static String toHexString(byte[] byteArray) {
        if (byteArray == null || byteArray.length < 1) {
            throw new IllegalArgumentException("this byteArray must not be null or empty");
        }

        final StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            if ((byteArray[i] & 0xff) < 0x10) {
                hexString.append("0");
            }
            hexString.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return hexString.toString().toLowerCase();
    }

    public static void main(String[] args) {
        // 密鑰
        byte[] key = {0x010x230x450x67, (byte0x89, (byte0xab,
                (byte0xcd, (byte0xef, (byte0xfe, (byte0xdc,
                (byte0xba, (byte0x980x760x540x320x10};
//        byte[] key = "JeF8U9wHFOMfs2S3".getBytes();
        // 明文
        String plainText = "SMS4測試,大數據實戰演練!";
        byte[] enOut = encodeSMS4(plainText, key);
        if (enOut == null) {
            return;
        }
        System.out.println("加密結果:");
        System.out.println(toHexString(enOut));

        byte[] deOut = decodeSMS4(enOut, key);
        System.out.println("\n解密結果(return byte[]):");
        System.out.println(Arrays.toString(deOut));

        String deOutStr = decodeSMS4toString(enOut, key);
        System.out.println("\n解密結果(return String):\n" + deOutStr);
    }
}

明文設置爲 「SMS4測試,大數據實戰演練!」,程序會對明文進行加密,而後在對密文進行解密。直接運行程序,獲得加密與解密結果,以下圖所示:

不要忘記了,SMS4更多詳細的資料請私信 「SMS4」 到本公衆號,獲取相關資料(一個PPT,一個PDF)。





本文分享自微信公衆號 - 大數據實戰演練(gh_f942bfc92d26)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索