当前位置: 首页 > 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.cnnetsun.cn/news/1835532.html

相关文章:

  • matlab代码:储能参与电能量—辅助服务调频市场联合出清代码。 本代码是电力市场出清的一个重要方向
  • Maxim传感器集线器通信库:跨平台C驱动与协议解析
  • 【仅限Q2释放】大模型成本健康度诊断矩阵(2026版):含17项KPI阈值、5类风险等级判定及自动修复建议
  • YOLO-Master 与 YOLO 开始畏
  • 探索tanx的3次方不定积分的两种解法:从基础到技巧
  • AI原生软件如何重构Scrum?:基于17家头部科技企业实证的4步渐进式适配框架
  • Jeager-One:面向Antares平台的ESP32多模通信SDK
  • ESP8266嵌入式Web配置框架:零代码运行时配置方案
  • 二分查找力扣题(leetcode)抖
  • 保姆级教程:用Node.js和Coturn搞定peerStream公网部署,让Unreal PixelStreaming跑起来
  • PINN求解一维热传导方程:3种神经网络架构(MLP、ResNet和Wang2020)的实战对比与优化策略
  • ROS 架构深度解析与工程实践
  • 为什么需要“双侧极限存在且相等”?
  • ADXL362超低功耗加速度计驱动开发与工程实践
  • 电价预测的模型进化论:从LSTM过拟合到Transformer实战
  • 脑电信号处理避坑指南:用MNE和Matplotlib生成时频图数据集时我踩过的那些雷
  • Ubuntu系统中Xmind8的安装与Java环境配置指南(实测可行)
  • 鱿鱼视频小说网站模板源码:快速搭建双模式资源站,轻松开启运营之路
  • 【仅限奇点大会注册开发者】:获取AI游戏实时行为树生成器v0.9.3(含未公开的NVIDIA Omniverse Bridge模块)
  • PyCharm社区版+Anaconda环境配置全攻略(避坑指南+清华镜像加速)
  • 多元高斯分布:条件分布的实际应用与推导解析
  • Windows效率神器PowerToys:30+免费工具让你的电脑生产力翻倍
  • 告别盲目探测!为你的Rockchip设备定制专属的Uboot SPL启动流程
  • STM32解析Futaba S.Bus协议:从硬件连接到数据解析全流程
  • Vue大屏自适应终极指南:v-scale-screen组件高效实战方案
  • 从“看图说话”到“像素级理解”:细数多模态大模型(MLLM)在工业质检与自动驾驶中的真实落地案例
  • Nginx 学习总结涝
  • 3分钟学会:用GetQzonehistory完整备份你的QQ空间历史说说
  • Cadence HDL原理图设计效率提升技巧:5个你可能不知道的实用功能
  • 实时行情系统设计:从协议选择到高可用架构,再到数据源选型匝