赞
踩
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESUtil { private static final String ALGORITHM = "AES"; private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding"; // 使用ECB模式和PKCS5Padding填充 // 使用AES加密 public static String encrypt(String key, String value) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encrypted); } // 使用AES解密 public static String decrypt(String key, String encrypted) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted)); return new String(original, StandardCharsets.UTF_8); } // 示例用法 public static void main(String[] args) throws Exception { String key = "your_16_byte_key_here_for_aes"; // AES密钥需要是16字节(128位) String value = "Hello, World!"; String encrypted = encrypt(key, value); System.out.println("Encrypted: " + encrypted); String decrypted = decrypt(key, encrypted); System.out.println("Decrypted: " + decrypted); } }
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>最新版本</version>
</dependency>
import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.engines.SM2Engine; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.SM2PrivateKeyParameters; import org.bouncycastle.crypto.params.SM2PublicKeyParameters; import org.bouncycastle.jce.ECNamedCurveGenParameterSpec; import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECParameterSpec; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; public class SM2Utils { static { Security.addProvider(new BouncyCastleProvider()); } // 生成SM2密钥对 public static KeyPair generateKeyPair() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC", "BC"); ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("sm2p256v1"); keyGen.initialize(new ECNamedCurveGenParameterSpec("sm2p256v1"), new java.security.SecureRandom()); return keyGen.generateKeyPair(); } // 此处仅为示例,实际使用中需要实现更完整的加密/解密/签名/验签逻辑 // 加密/解密、签名/验签的逻辑将涉及更复杂的参数设置和异常处理 // 注意:Bouncy Castle的org.bouncycastle.crypto包与Java的javax.crypto包不同 // 下面的示例仅为框架,并未包含完整的加密/解密逻辑 public static byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception { // 需要实现使用SM2公钥的加密逻辑 // ... return null; // 示例返回null,实际应返回加密后的数据 } public static byte[] decrypt(PrivateKey privateKey, byte[] cipherText) throws Exception { // 需要实现使用SM2私钥的解密逻辑 // ... return null; // 示例返回null,实际应返回解密后的数据 } public static byte[] sign(PrivateKey privateKey, byte[] data) throws Exception { // 需要实现使用SM2私钥的签名逻辑 // ... return null; // 示例返回null,实际应返回签名数据 } public static boolean verify(PublicKey publicKey, byte[] data, byte[] signature) throws Exception { // 需要实现使用SM2公钥的验签逻辑 // ... return false; // 示例返回false,实际应返回验签结果 } // ... 其他辅助方法或工具方法 ... }
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>1.77</version>
</dependency>
package com.mkj.publicservice.utils.smalgorithm; import org.bouncycastle.crypto.digests.SM3Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.pqc.math.linearalgebra.ByteUtils; import java.io.UnsupportedEncodingException; /** * @author: mkj */ public class Sm3Util { /** * SM3加密 * @param content 要加密的内容 */ public static String Sm3EncryptText(String content) throws UnsupportedEncodingException { byte[] bytes = content.getBytes(); byte[] hash = hash(bytes); String sm3 = ByteUtils.toHexString(hash); System.out.println("[Sm3EncryptText]sm3 hex:" + sm3); return sm3; } public static byte[] hash(byte[] srcData){ SM3Digest digest=new SM3Digest(); digest.update(srcData,0,srcData.length); byte[] bytes = new byte[digest.getDigestSize()]; digest.doFinal(bytes,0); return bytes; } /** * sm3算法通过密钥进行加密,不可逆加密 * @param keyText 密钥字符串 * @param plainText 需加密的明文字符串 * @return 加密后固定长度64的16进制字符串 */ public static String encryptByKey(String keyText, String plainText) { return ByteUtils.toHexString(encryptByKey(keyText.getBytes(), plainText.getBytes())); } /** * sm3算法通过密钥进行加密,不可逆加密 * @param keyByte 密钥数组 * @param plainByte 需加密的明文数组 * @return 加密后固定长度64的16进制数组 */ public static byte[] encryptByKey(byte[] keyByte, byte[] plainByte) { KeyParameter keyParameter = new KeyParameter(keyByte); SM3Digest sm3Digest = new SM3Digest(); HMac hMac = new HMac(sm3Digest); hMac.init(keyParameter); hMac.update(plainByte, 0, plainByte.length); byte[] result = new byte[hMac.getMacSize()]; hMac.doFinal(result, 0); return result; } /** * 主函数 * @param args */ public static void main(String[] args) throws UnsupportedEncodingException { Sm3EncryptText("ceshi001"); System.out.println(encryptByKey("key001","abc")); } }
package com.mkj.publicservice.utils.smalgorithm; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.pqc.math.linearalgebra.ByteUtils; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.AlgorithmParameters; import java.security.Key; import java.security.SecureRandom; import java.security.Security; import java.util.Arrays; /** * @author: mkj */ public class Sm4CbcUtils { static { Security.addProvider(new BouncyCastleProvider()); } private static final String ENCODING = "UTF-8"; public static final String ALGORITHM_NAME = "SM4"; // 加密算法/分组加密模式/分组填充方式 // PKCS5Padding-以8个字节为一组进行分组加密 // 定义分组加密模式使用:PKCS5Padding public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS5Padding"; // 128-32位16进制;256-64位16进制 public static final int DEFAULT_KEY_SIZE = 128; /** * 自动生成密钥 * * @return * @explain */ public static byte[] generateKey() throws Exception { return generateKey(DEFAULT_KEY_SIZE); } /** * 自动生成密钥 * @return * @throws Exception */ public static String generateKeyString() throws Exception { return ByteUtils.toHexString(generateKey()); } /** * @param keySize * @return * @throws Exception * @explain */ public static byte[] generateKey(int keySize) throws Exception { KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME); kg.init(keySize, new SecureRandom()); return kg.generateKey().getEncoded(); } /** * sm4加密 * * @param hexKey 16进制密钥(忽略大小写) * @param paramStr 待加密字符串 * @return 返回16进制的加密字符串 * @throws Exception * @explain 加密模式:CBC */ public static String encrypt(String hexKey, String paramStr) throws Exception { String result = ""; // 16进制字符串-->byte[] byte[] keyData = ByteUtils.fromHexString(hexKey); // String-->byte[] byte[] srcData = paramStr.getBytes(ENCODING); // 加密后的数组 byte[] cipherArray = encryptCbcPadding(keyData, srcData); // byte[]-->hexString result = ByteUtils.toHexString(cipherArray); return result; } /** * 加密模式之CBC * * @param key * @param data * @return * @throws Exception * @explain */ public static byte[] encryptCbcPadding(byte[] key, byte[] data) throws Exception { Cipher cipher = generateCbcCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.ENCRYPT_MODE, key); return cipher.doFinal(data); } /** * 加密模式之CBC * @param algorithmName * @param mode * @param key * @return * @throws Exception */ private static Cipher generateCbcCipher(String algorithmName, int mode, byte[] key) throws Exception { Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME); Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME); cipher.init(mode, sm4Key, generateIV()); return cipher; } /** * 生成iv * @return * @throws Exception */ public static AlgorithmParameters generateIV() throws Exception { //iv 为一个 16 字节的数组,这里采用和 iOS 端一样的构造方法,数据全为0 byte[] iv = new byte[16]; Arrays.fill(iv, (byte) 0x00); AlgorithmParameters params = AlgorithmParameters.getInstance(ALGORITHM_NAME); params.init(new IvParameterSpec(iv)); return params; } /** * sm4解密 * * @param hexKey 16进制密钥 * @param text 16进制的加密字符串(忽略大小写) * @return 解密后的字符串 * @throws Exception * @explain 解密模式:采用CBC */ public static String decrypt(String hexKey, String text) throws Exception { // 用于接收解密后的字符串 String result = ""; // hexString-->byte[] byte[] keyData = ByteUtils.fromHexString(hexKey); // hexString-->byte[] byte[] resultData = ByteUtils.fromHexString(text); // 解密 byte[] srcData = decryptCbcPadding(keyData, resultData); // byte[]-->String result = new String(srcData, ENCODING); return result; } /** * 解密 * * @param key * @param cipherText * @return * @throws Exception * @explain */ public static byte[] decryptCbcPadding(byte[] key, byte[] cipherText) throws Exception { Cipher cipher = generateCbcCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.DECRYPT_MODE, key); return cipher.doFinal(cipherText); } public static void main(String[] args) throws Exception { String str = "Hello, world" ; System.out.println("==========生成密钥=========="); String generateKey = generateKeyString(); System.out.println(generateKey); System.out.println("==========加密=========="); String encrypt = encrypt(generateKey, str); System.out.println(encrypt); System.out.println("==========解密=========="); String decrypt = decrypt(generateKey, encrypt); System.out.println(decrypt); } }
package com.mkj.publicservice.utils.smalgorithm; import cn.hutool.crypto.SmUtil; import cn.hutool.crypto.symmetric.SM4; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.pqc.math.linearalgebra.ByteUtils; import org.bouncycastle.util.encoders.Hex; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.Key; import java.security.SecureRandom; import java.security.Security; import java.util.Arrays; /** * @author: mkj */ public class Sm4EcbUtils { static { Security.addProvider(new BouncyCastleProvider()); } private static final String ENCODING = "UTF-8"; public static final String ALGORITHM_NAME = "SM4"; // 加密算法/分组加密模式/分组填充方式 // PKCS5Padding-以8个字节为一组进行分组加密 // 定义分组加密模式使用:PKCS5Padding public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding"; // 128-32位16进制;256-64位16进制 public static final int DEFAULT_KEY_SIZE = 128; /** * 自动生成密钥 * * @return * @explain */ public static String generateKey() throws Exception { return new String(Hex.encode(generateKey(DEFAULT_KEY_SIZE))); } /** * @param keySize * @return * @throws Exception * @explain */ public static byte[] generateKey(int keySize) throws Exception { KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME); kg.init(keySize, new SecureRandom()); return kg.generateKey().getEncoded(); } /** * 生成ECB暗号 * * @param algorithmName 算法名称 * @param mode 模式 * @param key * @return * @throws Exception * @explain ECB模式(电子密码本模式:Electronic codebook) */ private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception { Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME); Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME); cipher.init(mode, sm4Key); return cipher; } /** * sm4加密 * @param hexKey 16进制密钥(忽略大小写),也可自定义,注意如果不需要转化16进制,自行修改代码。 * byte[] keyData = ByteUtils.fromHexString(hexKey); * 改为 * byte[] srcData = hexKey.getBytes(ENCODING); * 验证方法为同样的道理 * @param paramStr 待加密字符串 * @return 返回16进制的加密字符串 * @explain 加密模式:ECB * 密文长度不固定,会随着被加密字符串长度的变化而变化 */ public static String encryptEcb(String hexKey, String paramStr) { try { String cipherText = ""; // 16进制字符串-->byte[] byte[] keyData = ByteUtils.fromHexString(hexKey); // String-->byte[] byte[] srcData = paramStr.getBytes(ENCODING); // 加密后的数组 byte[] cipherArray = encryptEcbPadding(keyData, srcData); // byte[]-->hexString cipherText = ByteUtils.toHexString(cipherArray); return cipherText; } catch (Exception e) { return paramStr; } } /** * 加密模式之Ecb * * @param key * @param data * @return * @throws Exception * @explain */ public static byte[] encryptEcbPadding(byte[] key, byte[] data) throws Exception { Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key); return cipher.doFinal(data); } /** * sm4解密 * * @param hexKey 16进制密钥 * @param cipherText 16进制的加密字符串(忽略大小写) * @return 解密后的字符串 * @throws Exception * @explain 解密模式:采用ECB */ public static String decryptEcb(String hexKey, String cipherText) { // 用于接收解密后的字符串 String decryptStr = ""; // hexString-->byte[] byte[] keyData = ByteUtils.fromHexString(hexKey); // hexString-->byte[] byte[] cipherData = ByteUtils.fromHexString(cipherText); // 解密 byte[] srcData = new byte[0]; try { srcData = decryptEcbPadding(keyData, cipherData); // byte[]-->String decryptStr = new String(srcData, ENCODING); } catch (Exception e) { e.printStackTrace(); } return decryptStr; } /** * 解密 * * @param key * @param cipherText * @return * @throws Exception * @explain */ public static byte[] decryptEcbPadding(byte[] key, byte[] cipherText) throws Exception { Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key); return cipher.doFinal(cipherText); } /** * 校验加密前后的字符串是否为同一数据 * * @param hexKey 16进制密钥(忽略大小写) * @param cipherText 16进制加密后的字符串 * @param paramStr 加密前的字符串 * @return 是否为同一数据 * @throws Exception * @explain */ public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception { // 用于接收校验结果 boolean flag = false; // hexString-->byte[] byte[] keyData = ByteUtils.fromHexString(hexKey); // 将16进制字符串转换成数组 byte[] cipherData = ByteUtils.fromHexString(cipherText); // 解密 byte[] decryptData = decryptEcbPadding(keyData, cipherData); // 将原字符串转换成byte[] byte[] srcData = paramStr.getBytes(ENCODING); // 判断2个数组是否一致 flag = Arrays.equals(decryptData, srcData); return flag; } public static void main(String[] args) { try { String paramStr = "Hello, world"; System.out.println("==========加密前源数据=========="); System.out.println(paramStr); // 生成32位16进制密钥 String key = generateKey(); System.out.println("==========生成key=========="); System.out.println(key); String cipher = encryptEcb(key, paramStr); System.out.println("==========加密串=========="); System.out.println(cipher); System.out.println("==========是否为同一数据=========="); System.out.println(verifyEcb(key, cipher, paramStr)); paramStr = decryptEcb(key, cipher); System.out.println("==========解密后数据=========="); System.out.println(paramStr); } catch (Exception e) { e.printStackTrace(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。