当前位置: 首页 > news >正文

BouncyCastle SM2/SM3/SM4

BouncyCastle SM2/SM3/SM4 为啥这些人命名的不是SM1, SM3 非对称;SM2 SM4 对称

<!-- BouncyCastle 国密核心依赖 --> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk18on</artifactId> <version>1.78.5</version> </dependency>
import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.security.Security; // 全局注册一次即可 static { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } }
import org.bouncycastle.crypto.digests.SM3Digest; import org.bouncycastle.util.encoders.Hex; /** * SM3 哈希加密 * @param data 明文 * @return 64位十六进制哈希串 */ public static String sm3Encrypt(String data) { byte[] srcData = data.getBytes(); SM3Digest sm3Digest = new SM3Digest(); sm3Digest.update(srcData, 0, srcData.length); byte[] digest = new byte[sm3Digest.getDigestSize()]; sm3Digest.doFinal(digest, 0); // 转为十六进制字符串 return Hex.toHexString(digest); } // 测试 public static void main(String[] args) { String text = "测试国密SM3加密"; String result = sm3Encrypt(text); System.out.println("SM3哈希值:" + result); }
import org.bouncycastle.crypto.engines.SM4Engine; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PKCS7Padding; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.encoders.Hex; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; /** * SM4 对称加密(CBC模式) */ public class SM4Util { private static final int SM4_KEY_LENGTH = 16; // SM4 密钥固定16字节 private static final int IV_LENGTH = 16; // 生成随机 SM4 密钥(16字节) public static String generateSm4Key() { byte[] key = new byte[SM4_KEY_LENGTH]; new SecureRandom().nextBytes(key); return Hex.toHexString(key); } // 生成随机 IV public static String generateIv() { byte[] iv = new byte[IV_LENGTH]; new SecureRandom().nextBytes(iv); return Hex.toHexString(iv); } /** * SM4 加密 */ public static String sm4Encrypt(String plainText, String keyHex, String ivHex) throws Exception { byte[] key = Hex.decode(keyHex); byte[] iv = Hex.decode(ivHex); byte[] data = plainText.getBytes(StandardCharsets.UTF_8); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CBCBlockCipher(new SM4Engine()), new PKCS7Padding()); cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv)); byte[] encrypted = new byte[cipher.getOutputSize(data.length)]; int len = cipher.processBytes(data, 0, data.length, encrypted, 0); len += cipher.doFinal(encrypted, len); return Hex.toHexString(encrypted, 0, len); } /** * SM4 解密 */ public static String sm4Decrypt(String cipherText, String keyHex, String ivHex) throws Exception { byte[] key = Hex.decode(keyHex); byte[] iv = Hex.decode(ivHex); byte[] data = Hex.decode(cipherText); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CBCBlockCipher(new SM4Engine()), new PKCS7Padding()); cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv)); byte[] decrypted = new byte[cipher.getOutputSize(data.length)]; int len = cipher.processBytes(data, 0, data.length, decrypted, 0); len += cipher.doFinal(decrypted, len); return new String(decrypted, 0, len, StandardCharsets.UTF_8); } // 测试 public static void main(String[] args) throws Exception { String text = "测试国密SM4加密"; String key = generateSm4Key(); String iv = generateIv(); String encrypt = sm4Encrypt(text, key, iv); String decrypt = sm4Decrypt(encrypt, key, iv); System.out.println("密钥:" + key); System.out.println("加密结果:" + encrypt); System.out.println("解密结果:" + decrypt); } }
import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.util.PrivateKeyFactory; import org.bouncycastle.crypto.util.PublicKeyFactory; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Hex; import java.security.Security; // SM2 工具类 public class SM2Util { static { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } } /** * 生成 SM2 密钥对(公钥+私钥) */ public static AsymmetricCipherKeyPair generateSm2KeyPair() { org.bouncycastle.crypto.generators.ECKeyPairGenerator generator = new org.bouncycastle.crypto.generators.ECKeyPairGenerator(); generator.init(new org.bouncycastle.crypto.params.ECKeyGenerationParameters( org.bouncycastle.jce.ECNamedCurveTable.getParameterSpec("sm2p256v1").getDomainParameters(), new java.security.SecureRandom() )); return generator.generateKeyPair(); } // 公钥转十六进制 public static String publicKeyToHex(ECPublicKeyParameters publicKey) { return Hex.toHexString(publicKey.getQ().getEncoded(false)); } // 私钥转十六进制 public static String privateKeyToHex(ECPrivateKeyParameters privateKey) { return Hex.toHexString(privateKey.getD().toByteArray()); } /** * SM2 公钥加密 */ public static String sm2Encrypt(String data, String publicKeyHex) throws Exception { ECPublicKeyParameters publicKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(Hex.decode(publicKeyHex)); org.bouncycastle.crypto.engines.SM2Engine engine = new org.bouncycastle.crypto.engines.SM2Engine(); engine.init(true, publicKey); byte[] encrypted = engine.processBlock(data.getBytes(), 0, data.getBytes().length); return Hex.toHexString(encrypted); } /** * SM2 私钥解密 */ public static String sm2Decrypt(String cipherText, String privateKeyHex) throws Exception { ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) PrivateKeyFactory.createKey(Hex.decode(privateKeyHex)); org.bouncycastle.crypto.engines.SM2Engine engine = new org.bouncycastle.crypto.engines.SM2Engine(); engine.init(false, privateKey); byte[] decrypted = engine.processBlock(Hex.decode(cipherText), 0, Hex.decode(cipherText).length); return new String(decrypted); } // 测试 public static void main(String[] args) throws Exception { // 生成密钥对 AsymmetricCipherKeyPair keyPair = generateSm2KeyPair(); ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic(); ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate(); String publicKeyHex = publicKeyToHex(publicKey); String privateKeyHex = privateKeyToHex(privateKey); String text = "测试国密SM2加密"; String encrypt = sm2Encrypt(text, publicKeyHex); String decrypt = sm2Decrypt(encrypt, privateKeyHex); System.out.println("公钥:" + publicKeyHex); System.out.println("私钥:" + privateKeyHex); System.out.println("加密:" + encrypt); System.out.println("解密:" + decrypt); } }

emo!!!!!国标加密解密

http://www.jsqmd.com/news/626206/

相关文章:

  • Three.js 3D热力图实现全解析(从原理到实战)
  • LibBriandIDF:ESP32上生产就绪的C++17嵌入式工具库
  • OBS多路推流插件窗口消失?三步快速找回+终极预防指南
  • 嵌入式VGM音频库:轻量级芯片级音源仿真与实时播放
  • BMP183气压传感器驱动开发与嵌入式实战指南
  • 3种实用方法:使用MediaCreationTool.bat绕过Windows 11硬件限制完全指南
  • 别只用来聊天了!手把手教你用PyCharm+Continue+DeepSeek,把代码审查、生成测试、重构都自动化
  • i18n 2026.04.11
  • STM32WLE5CCU6实战:从官方例程到第三方模块的PingPong通信移植详解
  • 性能测试基准
  • 2026装修改造哪家正规:厨房翻新改造/商铺装修改造/墙面翻新改造/旧房翻新改造/精装房装修改造/老房翻新改造/选择指南 - 优质品牌商家
  • 安全智能:MongoDB EF Core 提供程序中的可查询加密和向量搜索铰
  • 【国家级AI安全合规指南】:基于GB/T 44503-2024标准的6层对齐验证体系实战拆解
  • 2026年轨道交通电力电缆生产厂家推荐:涵中低压、低压、中压等厂家(4月版) - 品牌2026
  • ESP8266轻量级Homie物联网框架封装库
  • 3分钟学会使用Balena Etcher:最安全的镜像烧录工具
  • 基于Java Web的商铺租赁管理系统:从需求分析到模块实现的实战指南
  • 数据标注进阶:解决Label-Studio工具中的UTF-8编码与跨列标注难题
  • 把近万个源文件喂给AI之前,我先做了一件事猛
  • A4988步进电机驱动库深度解析与裸机控制实践
  • VSCode搜索优化:如何快速排除node_modules和.min.js文件(附完整配置代码)
  • Python类型提示系统mypy静态检查与运行时类型验证的集成
  • 需求管理中的用户故事与用例结合方法
  • 适配机器人全场景抓取,专业厂商技术方案与实力全面盘点 - 品牌2026
  • 高性能客服系统技术内幕:通过 SpinWait 自旋等待结构体提升高频消息分发性能挥
  • AX-12A舵机底层驱动与Dynamixel协议实战指南
  • Sunshine终极指南:5步搭建你的专属游戏串流服务器,畅享跨平台云端游戏体验
  • MC74HC595A移位寄存器驱动原理与嵌入式实战
  • 2026年旋转夹爪厂家怎么选?灵活旋转夹爪技术把控与选型要点解析 - 品牌2026
  • 阿里231滑块参数n逆向实战:从环境监测到轨迹模拟的完整解析