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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 惠普服务器磁盘阵列配置及故障修复「建议收藏」

    惠普服务器磁盘阵列配置及故障修复「建议收藏」设备上电开机,按键盘F10.稍等片刻进入开机界面》》》》》》惠普服务器磁盘阵列配置Raid1/Raid0惠普服务器磁盘阵列的设置是安装操作系统的先决条件。只有完成了磁盘阵列的设置才能正常使用。HPDL388Gen9系列,配两块HDD硬盘。步骤如下:https://jingyan.baidu.com/article/e3c78…

    2022年5月29日
    53
  • 加多宝为什么会输给王老吉_加多宝王老吉占比

    加多宝为什么会输给王老吉_加多宝王老吉占比如果评选世界营销战最激烈案例,2012年爆发的王老吉与加多宝之间的品牌大战一定榜上有名。那是一场由一个小小红罐引发的“血战”。一、缘起加、王之争的来龙动脉我就不细说了,大概起因是若干年前国企广药将其旗下的传统凉茶品牌“王老吉”部分(红罐)租给了与王老吉凉茶创始者后人有关的香港鸿道集团旗下的加多宝集团。这种做法本来十分普遍没啥特别,但没想到的是加多宝的市场运作能力超强,竟然在短短几年内将一种原来…

    2025年7月15日
    2
  • 2021-07-22MATLAB基于元胞自动机模型的传染病扩散模型

    2021-07-22MATLAB基于元胞自动机模型的传染病扩散模型MATLAB 基于元胞自动机模型的传染病扩散模型基本思路 地图矩阵可以分为两类 一类是健康人矩阵 一类是感染者矩阵 健康人感染后则落入感染者矩阵 感染者康复后则升上健康人矩阵通过建立三维矩阵 Track 在 x 轴和 y 轴之上加入时间轴形成三维 来追踪已感染的人的感染时间 从而判定康复 通过设置 NewMap 和 NewPatientMa 两个过渡矩阵来更新每次的随机移动 防止先更新的人在遍历过程中再次被选中导致一个回合内多次移动 将地图分为两种 一种是健康人地图 一种是病人地图 多个人可以在同一个点

    2025年11月5日
    0
  • 重定向与转发的区别以及实现_重定向与转发

    重定向与转发的区别以及实现_重定向与转发一、转发和重定向的区别request.getRequestDispatcher()是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;服务器内部转发,整个过程处于同一个请求当中。response.sendRedirect()则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接。这样,从浏览器的地址栏中可以看到跳转后的链接地址。不在同一个请求。重定向,实际上客户端会向服务器端发送两个请求。所以转发中数据的存取可以用request作用域:request.setAtt…

    2025年7月11日
    3
  • navicat for mysql如何导入sql文件_excel怎么把0显示出来

    navicat for mysql如何导入sql文件_excel怎么把0显示出来NavicatforMySQL导入excel文件_水里的鱼不会羡慕陆地爬行的动物-CSDN博客NavicatforMySQL是连接数据库的工具,可以更好地管理数据库。1.先连接连接名和主机名都是IP,本地连接名和主机名是localhost或127.0.0.1。-2.创建数据库及表表已经创建好了接下来就将含有学生信息的class.xls表导入到message表中2.1点击导入向导2.2表中我的数据放在sheet12.3这里我从第二行…

    2022年9月17日
    2
  • 小米9刷面具和模块[通俗易懂]

    小米9刷面具和模块[通俗易懂]准备工作:没解BL锁的需要先解锁1.按住音量键下和关机键进入Fastboot模式连接电脑2.这里使用奇兔刷机连接手机,中途会自动安装驱动,若安装驱动失败可使用驱动精灵或驱动人生手动安装驱动.安装完驱动后奇兔刷机会显示已经连接到手机开启root:1.下载twrphttps://twrp.me/xiaomi/xiaomimi9.html2.1.把Magisk-v20.4.zip和magisk-taichi

    2022年6月4日
    113

发表回复

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

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