sm4 前后端 加密_sm4加密[通俗易懂]

sm4 前后端 加密_sm4加密[通俗易懂]前言项目里需要用到sm4加密,在这里记录一下(springboot)。依赖bouncycastleorg.bouncycastlebcmail-jdk15on1.66cn.hutoolhutool-all5.4.1代码直接贴代码,可以根据自己的需要封装相对应的代码逻辑。//需要注意的是,使用KeyGenerator生成密钥种子的时候,windows和linux上会产生不一致。//例如:KeyGen…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

前言

项目里需要用到sm4加密,在这里记录一下(springboot)。

依赖

bouncycastle

org.bouncycastle

bcmail-jdk15on

1.66

cn.hutool

hutool-all

5.4.1

代码

直接贴代码,可以根据自己的需要封装相对应的代码逻辑。

//需要注意的是,使用KeyGenerator生成密钥种子的时候,windows和linux上会产生不一致。

//例如:

KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, PROVIDER_NAME);

SecureRandom random = new SecureRandom();

if(null != seed && !””.equals(seed)){

random.setSeed(seed.getBytes());

}

kg.init(keySize, random);

//解决办法

SecureRandom random = SecureRandom.getInstance(“SHA1PRNG”);

import cn.hutool.core.util.HexUtil;

import com.spinfo.common.constants.UserConstants;

import com.spinfo.controller.UserController;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import org.bouncycastle.util.encoders.Base64;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.util.DigestUtils;

import javax.crypto.*;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import java.security.*;

import java.util.Arrays;

public class SM4Util {

private static Logger logger = LoggerFactory.getLogger(SM4Util.class);

private static final String PROVIDER_NAME = “BC”;

public static final String ALGORITHM_NAME = “SM4”;

public static final String ALGORITHM_NAME_ECB_PADDING = “SM4/ECB/PKCS5Padding”;

public static final String ALGORITHM_NAME_CBC_PADDING = “SM4/CBC/PKCS5Padding”;

public static final String DEFAULT_KEY = “random_seed”;

public static final int DEFAULT_KEY_SIZE = 128;

private static final int ENCRYPT_MODE = 1;

private static final int DECRYPT_MODE = 2;

static {

Security.addProvider(new BouncyCastleProvider());

}

public static byte[] generateKey() throws NoSuchAlgorithmException, NoSuchProviderException {

return generateKey(DEFAULT_KEY, DEFAULT_KEY_SIZE);

}

public static byte[] generateKey(String seed) throws NoSuchAlgorithmException, NoSuchProviderException {

return generateKey(seed, DEFAULT_KEY_SIZE);

}

public static byte[] generateKey(String seed, int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {

KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, PROVIDER_NAME);

SecureRandom random = SecureRandom.getInstance(“SHA1PRNG”);

if(null != seed && !””.equals(seed)){

random.setSeed(seed.getBytes());

}

kg.init(keySize, random);

return kg.generateKey().getEncoded();

}

/**

* ecb 加密

* @param key

* @param data

*/

public static byte[] encryptEcbPadding(byte[] key, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {

Cipher cipher = generateEcbCipher(ENCRYPT_MODE, key);

return cipher.doFinal(data);

}

/**

* ecb 解密

* @param key

* @param cipherText

*/

public static byte[] decryptEcbPadding(byte[] key, byte[] cipherText) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {

Cipher cipher = generateEcbCipher(DECRYPT_MODE, key);

return cipher.doFinal(cipherText);

}

/**

* cbc 加密

* @param key

* @param data

*/

public static byte[] encryptCbcPadding(byte[] key, byte[] iv, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {

Cipher cipher = generateCbcCipher(ENCRYPT_MODE, key, iv);

return cipher.doFinal(data);

}

public static String encryptCbcPaddingString(byte[] key, byte[] iv, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {

Cipher cipher = generateCbcCipher(ENCRYPT_MODE, key, iv);

byte[] result = cipher.doFinal(data);

return Base64.toBase64String(result);

}

/**

* cbc 解密

* @param key

* @param iv

* @param cipherText

*/

public static byte[] decryptCbcPadding(byte[] key, byte[] iv, String cipherText) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException {

byte[] cipherBytes = Base64.decode(cipherText);

Cipher cipher = generateCbcCipher(DECRYPT_MODE, key, iv);

return cipher.doFinal(cipherBytes);

}

public static byte[] decryptCbcPadding(byte[] key, byte[] iv, byte[] cipherText) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException {

Cipher cipher = generateCbcCipher(DECRYPT_MODE, key, iv);

return cipher.doFinal(cipherText);

}

/**

* ecb cipher

* @param mode

* @param key

* @return

*/

private static Cipher generateEcbCipher(int mode, byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException {

Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, PROVIDER_NAME);

Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);

cipher.init(mode, sm4Key);

return cipher;

}

/**

* cbc cipher

* @param mode

* @param key

* @return

*/

private static Cipher generateCbcCipher(int mode, byte[] key, byte[] iv) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {

Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_CBC_PADDING, PROVIDER_NAME);

Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);

IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

cipher.init(mode, sm4Key, ivParameterSpec);

return cipher;

}

/**

* ecb 加密 times 次

* @param data

* @param salt

* @param times

* @return=

*/

public static String encryptEcbDataTimes(String data, String salt, int times) throws GeneralSecurityException {

try {

byte[] key = HexUtil.decodeHex(salt);

byte[] bytes = data.getBytes();

for(int i = 0; i < times; ++i) {

bytes = encryptEcbPadding(key, bytes);

}

data = Base64.toBase64String(bytes);

return data;

} catch (BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException | NoSuchProviderException | NoSuchAlgorithmException | InvalidKeyException var5) {

throw new GeneralSecurityException(“SM4加密失败”);

}

}

/**

* ecb 解密 times 次

* @param data

* @param salt

* @param times

* @return

* @throws GeneralSecurityException

*/

public static String decryptEcbDataTimes(String data, String salt, int times) throws GeneralSecurityException {

try {

byte[] bytes = Base64.decode(data);

byte[] key = HexUtil.decodeHex(salt);

for(int i = 0; i < times; ++i) {

bytes = decryptEcbPadding(key, bytes);

}

data = new String(bytes);

return data;

} catch (BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException | NoSuchProviderException | NoSuchAlgorithmException | InvalidKeyException var5) {

throw new GeneralSecurityException(“SM4解密失败”);

}

}

/**

* cbc 加密 times 次

* @param data

* @param salt

* @param times

* @return=

*/

public static String encryptCbcDataTimes(String data, String salt, int times) {

try {

byte[] iv = generateKey();

byte[] key = generateKey(salt);

byte[] bytes = data.getBytes();

Cipher cipher = generateCbcCipher(ENCRYPT_MODE, key, iv);

for(int i = 0; i < times; ++i) {

bytes = cipher.doFinal(bytes);

}

data = Base64.toBase64String(bytes);

return data;

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

/**

* cbc 解密 times 次

* @param data

* @param salt

* @param times

* @return

* @throws GeneralSecurityException

*/

public static String decryptCbcDataTimes(String data, String salt, int times) throws GeneralSecurityException {

try {

byte[] iv = generateKey();

byte[] bytes = Base64.decode(data);

byte[] key = generateKey(salt);

Cipher cipher = generateCbcCipher(ENCRYPT_MODE, key, iv);

for(int i = 0; i < times; ++i) {

bytes = cipher.doFinal(bytes);

}

data = new String(bytes);

return data;

} catch (BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException | NoSuchProviderException | NoSuchAlgorithmException | InvalidKeyException var5) {

throw new GeneralSecurityException(“SM4解密失败”);

}

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/185313.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • git命令大全(非常齐全)[通俗易懂]

    git命令大全(非常齐全)[通俗易懂]git命令大全

    2022年7月14日
    13
  • aix 关闭端口

    aix 关闭端口关掉对应的应用程序,则端口就自然关闭了,如:"kill-9PID"(PID:进程号)如:   通过"netstat-anp|grepssh"有显示:   tcp0127.0.0.1:21210.0.0.0:*LISTEN7546/ssh则:   "kill-97546" 1.netstat-Aan|grep&lt;portnumber&gt;…

    2022年7月20日
    13
  • 别了,等待

    别了,等待别了,等待

    2022年4月23日
    28
  • 注会综合记忆锦囊:手绘PEST模型,记忆可以这样玩「建议收藏」

    注会综合记忆锦囊:手绘PEST模型,记忆可以这样玩「建议收藏」【】综合的记忆量非常庞大,且看小萌有妙招,通过“关键词”和“手绘图”带你一起巧记忆。一、PEST宏观环境分析:4项1.政治因素:4项(1)执政党所持的态度和推行的基本政策(2)企业所在国家和地区的政局稳定状况(3)政府行为对企业的影响(4)各政治利益集团对企业活动产生的影响2.法律环境因素:4项(1)国家司法机关和执法机关(2)国际法所规定的国际法律环境和目标国

    2022年5月23日
    34
  • centos7安装python3.7_安装python教程

    centos7安装python3.7_安装python教程文章目录前言环境&组件说明组件用途说明准备阶段安装步骤详细步骤准备安装安装Python异常处理异常信息原因分析处理方法小技巧前言工作需要,服务器不能连接外网,因此需要离线安装。推荐在线安装,参考。环境&组件说明操作系统:CentOSLinuxrelease7.4.1708(Core)操作系统安装包:CentOS-7-x86_64-Minimal-1708.isoPython版本:3.8.5pip版本:20.1.1virtualenv版本:20.4.2组件用途说

    2022年9月25日
    0
  • 数列极限定义详解「建议收藏」

    数列极限定义详解「建议收藏」数列极限的定义个人感觉不太好理解,我看了两天的教程才彻底明白数列极限的定义。在一般的教材里数列极限的定义为这说的比较抽象,我半天都理解不了N是怎么来的,n与N有什么区别,为什么要用去减a,这里我对自己的疑问做了个总结。首先是为什么要用去减a,两个数之间的接近程度可以用两个之差的绝对值来度量,差值越小,两个数就越接近(说法来源于《高等数学》同济大学)。两个数的接近程度小于任给的正数​…

    2022年4月29日
    34

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号