Java SM2 加密解密实现教程 - Bouncy Castle 库示例
要在Java中实现SM2加密,可以使用Bouncy Castle库。以下是一个简单的示例代码:\n\njava\nimport org.bouncycastle.crypto.AsymmetricCipherKeyPair; \nimport org.bouncycastle.crypto.params.ECPrivateKeyParameters; \nimport org.bouncycastle.crypto.params.ECPublicKeyParameters; \nimport org.bouncycastle.crypto.util.PrivateKeyFactory; \nimport org.bouncycastle.crypto.util.PublicKeyFactory; \nimport org.bouncycastle.jce.provider.BouncyCastleProvider; \nimport org.bouncycastle.util.encoders.Base64; \nimport org.bouncycastle.util.encoders.Hex; \n\nimport java.security.Security; \n\npublic class SM2EncryptionExample { \n\n public static void main(String[] args) throws Exception { \n // 添加Bouncy Castle作为Provider \n Security.addProvider(new BouncyCastleProvider()); \n\n // 生成SM2密钥对 \n AsymmetricCipherKeyPair keyPair = SM2Utils.generateKeyPair(); \n\n // 获取公钥和私钥 \n ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic(); \n ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate(); \n\n // 将公钥和私钥转换为Base64编码的字符串 \n String publicKeyStr = Base64.toBase64String(publicKey.getQ().getEncoded(false)); \n String privateKeyStr = Hex.toHexString(privateKey.getD().toByteArray()); \n\n System.out.println("公钥:" + publicKeyStr); \n System.out.println("私钥:" + privateKeyStr); \n\n // 加密明文 \n String plaintext = "Hello, SM2!"; \n byte[] ciphertext = SM2Utils.encrypt(publicKey, plaintext.getBytes()); \n\n // 将密文转换为Base64编码的字符串 \n String ciphertextStr = Base64.toBase64String(ciphertext); \n System.out.println("密文:" + ciphertextStr); \n\n // 解密密文 \n byte[] decryptedText = SM2Utils.decrypt(privateKey, Base64.decode(ciphertextStr)); \n\n System.out.println("解密结果:" + new String(decryptedText)); \n } \n} \n \n\n上述示例代码中,我们首先添加Bouncy Castle作为Provider,并使用SM2Utils.generateKeyPair()生成SM2密钥对。然后,我们将公钥和私钥转换为Base64编码的字符串,并输出到控制台。 \n\n接下来,我们使用SM2Utils.encrypt()函数对明文进行加密,并将密文转换为Base64编码的字符串进行输出。最后,我们使用SM2Utils.decrypt()函数对密文进行解密,并输出解密结果。 \n\n请注意,上述代码中的SM2Utils类需要自己实现,你可以根据SM2加密算法的规范来编写该类。
原文地址: https://www.cveoy.top/t/topic/pseE 著作权归作者所有。请勿转载和采集!