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源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索