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解密失败”);

}

}

}

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 虚拟机无法在windows10上运行_虚拟机中安装windows10详细教程

    虚拟机无法在windows10上运行_虚拟机中安装windows10详细教程虚拟机中安装Windodxp系统,可能会存在一些问题,现在把安装中碰到的问题和解决方法总结如下: 问题1:outputerrorfiletothefollowinglocation:问题2:Exiting Intel PXE ROM.OperatingSystemnotfound问题1和问题2解决方法:需要对虚拟机进行分区,分配一个主分区,

  • charles乱码怎么解决_抓包精灵乱码

    charles乱码怎么解决_抓包精灵乱码前言当使用Charles抓包时,发现数据都是乱码,这时需要安装证书解决办法1.点击charles窗口,点击左上角Help->SSLProxying→InstallCharles

  • Qt中的角度转弧度[通俗易懂]

    Qt中的角度转弧度[通俗易懂]在Qt中,qAsin(),qAtan2()等三角函数的返回值是弧度而不是角度,因此要将弧度转化为角度。弧度=角度*Pi/180以qAtan()函数为例qrealqAtan(qrealv)Returnsthearctangentofvasanangleinradians.Arctangentistheinverseoperationoftangent….

  • el-upload多文件上传_vue 界面

    el-upload多文件上传_vue 界面vue使用element-ui的el-upload实现上传文件到后台的功能1.添加el-upload控件<el-upload:action=”action”:file-list=”modeList”:http-request=”modeUpload”><el-buttonsize=”small”type=”primary…

  • Laravel 上传excel,读取并写入数据库 (实现自动建表、存记录值

    Laravel 上传excel,读取并写入数据库 (实现自动建表、存记录值

    2021年10月24日
  • 原来都是freesync惹的锅「建议收藏」

    原来都是freesync惹的锅「建议收藏」今天贪便宜入了一款创维的2k显示屏,开始用N卡+DP线驱动得挺稳定,然后手闲开了freesync,结果就各种闪烁、条纹。最无奈的是显示器菜单里freesycn选项竟然灰了,关不上了,呜呼!在打算退货前,胡乱操作了一通,例如,菜单里恢复出厂设置,无果。用HDMI线降分辨率、降刷新率,无果。进入工程界面(按住M在POWERON),没敢乱调,退出。然后再在菜单里恢复出厂设置…….最后菜单中选模式为文本,重新DP线接入,竟然freesync被神奇地关闭了。之后,2k屏就再没闪过,千万不要乱动free

发表回复

您的电子邮箱地址不会被公开。

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