使用Bouncy Castle(pom版本:bcprov-jdk15on 1.59)中SM4 加密解密算法 ECB

SM4 加密算法 加密 SM4算法是一种分组密码算法。其分组长度为128bit,密钥长度也为128bit。

加密算法与密钥扩展算法均采用32轮非线性迭代结构,以字(32位)为单位进行加密运算,每一次迭代运算均为一轮变换函数F。SM4算法加/解密算法的结构相同,只是使用轮密钥相反,其中解密轮密钥是加密轮密钥的逆序。

public class encryption_decrypt {
     

    static {
     
        Security.addProvider(new BouncyCastleProvider());
    }
    private static final String ENCODING = "UTF-8";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用:PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    // 128-32位16进制;256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
     
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }
    public static String encryptEcb(byte[] hexKey, String paramStr) throws Exception {
     
        String cipherText = null;
        byte[] keyData = hexKey;

        byte[] srcData = paramStr.getBytes(ENCODING);
        byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
        cipherText = Base64.getEncoder().encodeToString(cipherArray);
       return cipherText;
    }

    public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
     
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    public static String decryptEcb(byte[] hexKey, String cipherText) throws Exception {
     
        String decryptStr = "";
        byte[] keyData = hexKey;
        byte[] cipherData = Base64.getDecoder().decode(cipherText);
        byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
        decryptStr = new String(srcData, ENCODING);
        return decryptStr;
    }
    public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
     
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }
    public static boolean verifyEcb(byte[] hexKey, String cipherText, String paramStr) throws Exception {
     
        boolean flag = false;
        byte[] keyData = hexKey;
        byte[] cipherData = Base64.getDecoder().decode(cipherText);
        byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
        byte[] srcData = paramStr.getBytes(ENCODING);
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }
}

你可能感兴趣的:(Bouncy,Castle,java)