Implementation of Cryptographic Algorithms: AES, 3DES, RSA, SM2, SM3, SM4

Click the blue text above “Programming Diary” to follow below Implementation of Cryptographic Algorithms: AES, 3DES, RSA, SM2, SM3, SM4Implementation of Cryptographic Algorithms: AES, 3DES, RSA, SM2, SM3, SM4Implementation of Cryptographic Algorithms: AES, 3DES, RSA, SM2, SM3, SM4

National secret algorithms: These are algorithms independently developed by our country to reduce excessive reliance on foreign technology. National secret refers to the domestic cryptographic algorithms recognized by the National Cryptography Administration. The following is the specific correspondence:

Symmetric algorithms: AES, DES, SM4
Asymmetric algorithms: RSA, SM2
Hash algorithms: MD5, SHA-1, SM3

Introduction to national secret algorithms: Still using DES? Try domestic encryption algorithms.

OK, here are the commonly used encryption algorithm implementations. Without further ado, since you are here, it means you already understand these algorithms. This article can serve as a reference dictionary.

Among them, AES, 3DES, and RSA are implemented in Java by default, while the national secret algorithms SM2, SM3, and SM4 require additional dependencies:

Dependency: <!-- National secret algorithms --> <dependency>    <groupId>org.bouncycastle</groupId>    <artifactId>bcprov-jdk15on</artifactId>    <version>1.58</version></dependency>

AES

AES:

/** *  */package com.xy.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
/** * */public class Aes implements IAlgorithm{
    private static final String ALGORITHM_AES = "AES";
    private static final int keysize = 128;
    private static final String CHARSET_UTF8 = "utf-8";
    private static final Logger LOGGER = LoggerFactory.getLogger(Aes.class);
    /**     * Generate key     * @param keySrc     * @return     * @throws NoSuchAlgorithmException      * @throws UnsupportedEncodingException      */    public String generateKey(String keySrc) {       try{          if(keySrc ==null || keySrc.isEmpty()){             keySrc = String.valueOf(System.currentTimeMillis());          }          KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM_AES);          SecureRandom random = new SecureRandom(keySrc.getBytes(CHARSET_UTF8));          keyGen.init(keysize,random);          SecretKey secretKey = keyGen.generateKey();          return Base64.getEncoder().encodeToString(secretKey.getEncoded());       }catch(Exception e){          LOGGER.error("Key generation exception",e);       }       return keySrc;    }
    @Override    public String[] generateKeyPair(String key) {       return new String[0];    }
    private SecretKey strKeyToSecretKey(String strKey){       byte[] bytes = Base64.getDecoder().decode(strKey);       SecretKeySpec secretKey = new SecretKeySpec(bytes,ALGORITHM_AES);       return secretKey;    }
    private byte[] encryptAES(byte[] content,SecretKey secretKey) throws NoSuchAlgorithmException,            NoSuchPaddingException,InvalidKeyException,IllegalBlockSizeException,BadPaddingException{       Cipher cipher = Cipher.getInstance(ALGORITHM_AES);       cipher.init(Cipher.ENCRYPT_MODE,secretKey);       return cipher.doFinal(content);    }
    private byte[] decryptAES(byte[] content,SecretKey secretKey) throws NoSuchAlgorithmException,            NoSuchPaddingException,InvalidKeyException,IllegalBlockSizeException,BadPaddingException{       Cipher cipher = Cipher.getInstance(ALGORITHM_AES);       cipher.init(Cipher.DECRYPT_MODE,secretKey);       return cipher.doFinal(content);    }
    public String encrypt(String content,String secretKey){       try{          if(content==null || content.isEmpty() || secretKey == null){             return null;          }          byte[] des = encryptAES(content.getBytes(CHARSET_UTF8),strKeyToSecretKey(secretKey));          return Base64.getEncoder().encodeToString(des);       }catch(Exception e){          LOGGER.error("Encryption exception",e);       }       return content;    }
    public String decrypt(String ciphertext,String secretKey){       try{             if(ciphertext ==null || ciphertext.isEmpty() || secretKey == null){             return null;          }          return new String(decryptAES(Base64.getDecoder().decode(ciphertext),strKeyToSecretKey(secretKey)),                  CHARSET_UTF8);       }catch(Exception e){          LOGGER.error("Decryption exception",e);       }       return ciphertext;    }
    public static void main(String[] args){       IAlgorithm algo = new Aes();       String data = "For the sake of randomness, Carrefour in the two sides of the strait, I forgot 23ss, I am aaaaaaaaaaaaaa";       String keySrc = "adsdfssdfsgggee";       String keyStr = algo.generateKey(keySrc);       System.err.println("keySrc:" + keySrc);       System.err.println("Key:" + keyStr);       String ciphertext = algo.encrypt(data,keyStr);       System.err.println("Encrypted ciphertext length:" + ciphertext.length() + ", ciphertext:" + ciphertext);       String deStr = algo.decrypt(ciphertext,keyStr);       System.err.println("Decrypted plaintext:" + deStr);    }

3DES

3DES:

package com.xy.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
/** * 3DES Data Encryption Tool */public class TripleDes implements IAlgorithm{    //Define encryption algorithm, can use DES, DESede, Blowfish    private static final String Algorithm = "DESede";    private static final String CHARSET_UTF8 = "utf-8";    private static final int keysize = 112;    private static final Logger LOGGER = LoggerFactory.getLogger(TripleDes.class);    /**     * Generate key     * @param keySrc     * @return     * @throws NoSuchAlgorithmException      * @throws UnsupportedEncodingException      */    public String generateKey(String keySrc){       try{          if(keySrc==null || keySrc.isEmpty()){             keySrc = String.valueOf(System.currentTimeMillis());          }          KeyGenerator keyGen = KeyGenerator.getInstance(Algorithm);          SecureRandom random = new SecureRandom(keySrc.getBytes(CHARSET_UTF8));          keyGen.init(keysize,random);          SecretKey secretKey = keyGen.generateKey();          return Base64.getEncoder().encodeToString(secretKey.getEncoded());       }catch(Exception e){          LOGGER.error("Key generation exception",e);       }       return keySrc;    }
    @Override    public String[] generateKeyPair(String key) {       return new String[0];    }
    private SecretKey strKeyToSecretKey(String strKey){       byte[] bytes = Base64.getDecoder().decode(strKey);       SecretKeySpec secretKey = new SecretKeySpec(bytes,Algorithm);       return secretKey;    }
    /**     * Encrypt src content     * @param         * @param src     Encryption object     * @return     */    private byte[] encryptMode(SecretKey desKey,byte[] src) throws NoSuchPaddingException,            NoSuchAlgorithmException,InvalidKeyException,BadPaddingException,IllegalBlockSizeException{        //Encrypt        Cipher c = Cipher.getInstance(Algorithm);        c.init(Cipher.ENCRYPT_MODE, desKey);        byte[] enc = c.doFinal(src);        return enc;    }
    public String encrypt(String content,String key){       try{          SecretKey secretKey = strKeyToSecretKey(key);          byte[] src = content.getBytes(CHARSET_UTF8);          return Base64.getEncoder().encodeToString(encryptMode(secretKey,src));       }catch(Exception e){          LOGGER.error("Encryption exception.",e);       }       return content;    }
    /**     * Decrypt content     *     * @param key   Key     * @param src     Decryption object     * @return     */    private byte[] decryptMode(SecretKey key,byte[] src) throws NoSuchPaddingException,NoSuchAlgorithmException,            InvalidKeyException,BadPaddingException,IllegalBlockSizeException{        // Decrypt        Cipher c = Cipher.getInstance(Algorithm);       c.init(Cipher.DECRYPT_MODE,key);        byte[] dec = c.doFinal(src);        return dec;    }
    public String decrypt(String ciphertext,String key){       SecretKey secretKey = strKeyToSecretKey(key);       byte[] mw = Base64.getDecoder().decode(ciphertext);       try{          return new String(decryptMode(secretKey,mw),CHARSET_UTF8);       }catch(Exception e){          LOGGER.error("Decryption exception.",e);       }       return ciphertext;    }
    public static void main(String[] args) throws UnsupportedEncodingException{       try{          IAlgorithm algo = new TripleDes();          String keyStr = "4kj0da65235264c3364e9326";          keyStr = algo.generateKey(keyStr);          System.err.println("Key encrypted:" + keyStr);          String src = "alslfjladflkkasfeweeeeeeeeeeww我了呃呃呃呃呃呃呃呃呃呃呃呃呃呃呃呃呃呃www";          System.err.println("Plaintext length:" + src.length());          src = algo.encrypt(src,keyStr);          System.out.println("Encrypted string:" + src);          System.err.println("Ciphertext length:" + src.length());          // src="cIpMf3I2rH58wNsCTu8fOcnr0yRyj8/17i/lOKUsZiOtICxbKYvD0jj0ptE5P9+PYZsLDlXw0QTb9mrLSpXlOlk4NJuYh9VNSQk+XYNzkkY=";          src = algo.decrypt(src,keyStr);          System.out.println("Decrypted string:" + src);       }catch(Exception e){          // TODO Auto-generated catch block          e.printStackTrace();       }    }

RSA

RSA:

package com.xy.test;
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;
public class RSA {
    public static KeyPair generateKeyPair() throws Exception {        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");        keyPairGenerator.initialize(2048); // Key length is 2048 bits        return keyPairGenerator.generateKeyPair();    }
    public static byte[] encrypt(String plainText, PublicKey publicKey) throws Exception {        Cipher cipher = Cipher.getInstance("RSA");        cipher.init(Cipher.ENCRYPT_MODE, publicKey);        return cipher.doFinal(plainText.getBytes());    }
    public static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey) throws Exception {        Cipher cipher = Cipher.getInstance("RSA");        cipher.init(Cipher.DECRYPT_MODE, privateKey);        return cipher.doFinal(encryptedBytes);    }
    public static byte[] sign(String plainText, PrivateKey privateKey) throws Exception {        Signature signature = Signature.getInstance("SHA256withRSA");        signature.initSign(privateKey);        signature.update(plainText.getBytes());        return signature.sign();    }
    public static boolean verify(String plainText, byte[] signatureBytes, PublicKey publicKey) throws Exception {        Signature signature = Signature.getInstance("SHA256withRSA");        signature.initVerify(publicKey);        signature.update(plainText.getBytes());        return signature.verify(signatureBytes);    }
    public static void main(String[] args) throws Exception {        String plainText = "Hello, World!";
        // Generate key pair        KeyPair keyPair = generateKeyPair();
        // Get public and private keys        PublicKey publicKey = keyPair.getPublic();        PrivateKey privateKey = keyPair.getPrivate();        System.out.println("Public Key:" + publicKey);
        System.out.println("Private Key:" + privateKey);
        // Encrypt using public key        byte[] encryptedBytes = encrypt(plainText, publicKey);
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Ciphertext: " + encryptedText);
        // Decrypt using private key        byte[] decryptedBytes = decrypt(encryptedBytes, privateKey);
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted: " + decryptedText);
        // Sign using private key        byte[] signatureBytes = sign(plainText, privateKey);
        String signatureText = Base64.getEncoder().encodeToString(signatureBytes);
        System.out.println("Private Key Signature: " + signatureText);
        // Verify signature using public key        boolean isVerified = verify(plainText, signatureBytes, publicKey);
        System.out.println("Public Key Verify Signature: " + isVerified);
    }}

SM2

SM2:

package com.xy.util;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/** * @ClassName SM2 * @Description  SM2 encryption tool to replace RSA, belongs to asymmetric encryption, requires public and private keys * @Author xy * @Version 1.0 **/public class SM2 implements  IAlgorithm{    private static final String CHARSET_UTF8 = "utf-8";    private static final String STD_NAME = "sm2p256v1";    private static final String ALGORITHM = "EC";    private static final Logger LOGGER = LoggerFactory.getLogger(SM2.class);
    /**     * Generate national secret public and private key pair     *     * @return     * @throws Exception     */    public String[] generateKeyPair(String keySrc)  {        String[] result =new String[2] ;        try {            KeyPairGenerator keyPairGenerator = null;            if(keySrc==null || keySrc.isEmpty()){                keySrc = String.valueOf(System.currentTimeMillis());            }            SecureRandom secureRandom = new SecureRandom(keySrc.getBytes(CHARSET_UTF8));            ECGenParameterSpec sm2Spec = new ECGenParameterSpec(STD_NAME);            keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, new BouncyCastleProvider());            keyPairGenerator.initialize(sm2Spec);            keyPairGenerator.initialize(sm2Spec, secureRandom);            KeyPair keyPair = keyPairGenerator.generateKeyPair();            PrivateKey privateKey = keyPair.getPrivate();            PublicKey publicKey = keyPair.getPublic();            //String[0] Public Key            //String[1] Private Key           result = new String[]{                   new String(Base64.getEncoder().encode(publicKey.getEncoded()))                   , new String(Base64.getEncoder().encode(privateKey.getEncoded()))           };        }catch (Exception e){            LOGGER.error("Key generation exception",e);        }        return result;    }
    /**     * Convert Base64 encoded public key string to PublicKey object     *     * @param publicKey     * @return     */    private static PublicKey createPublicKey(String publicKey) {        PublicKey publickey = null;        try {            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, new BouncyCastleProvider());            publickey = keyFactory.generatePublic(publicKeySpec);        } catch (Exception e) {            LOGGER.error("Convert to PublicKey object exception",e);        }        return publickey;    }
    /**     * Convert Base64 encoded private key string to PrivateKey object     *     * @param privateKey     * @return     */    private static PrivateKey createPrivateKey(String privateKey) {        PrivateKey publickey = null;        try {            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, new BouncyCastleProvider());            publickey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);        } catch (Exception e) {            LOGGER.error("Convert to PrivateKey object exception",e);        }        return publickey;    }
    @Override    public String encrypt(String data, String key) {        PublicKey publicKey = createPublicKey(key);        byte[] bytes = data.getBytes(StandardCharsets.UTF_8);        ECPublicKeyParameters localECPublicKeyParameters = null;
        if (publicKey instanceof BCECPublicKey) {            BCECPublicKey localECPublicKey = (BCECPublicKey) publicKey;            ECParameterSpec localECParameterSpec = localECPublicKey.getParameters();            ECDomainParameters localECDomainParameters = new ECDomainParameters(localECParameterSpec.getCurve(),                    localECParameterSpec.getG(), localECParameterSpec.getN());            localECPublicKeyParameters = new ECPublicKeyParameters(localECPublicKey.getQ(), localECDomainParameters);        }
        SM2Engine localSM2Engine = new SM2Engine();        localSM2Engine.init(true, new ParametersWithRandom(localECPublicKeyParameters, new SecureRandom()));        byte[] arrayOfByte2;        try {            arrayOfByte2 = localSM2Engine.processBlock(bytes, 0, bytes.length);        } catch (InvalidCipherTextException e) {            LOGGER.error("Encryption exception",e);            return null;        }
        return Base64.getEncoder().encodeToString(arrayOfByte2);    }
    @Override    public String decrypt(String data, String key) {        PrivateKey privateKey = createPrivateKey(key);        byte[] encodeData = Base64.getDecoder().decode(data);        SM2Engine localSM2Engine = new SM2Engine();        BCECPrivateKey sm2PriK = (BCECPrivateKey) privateKey;        ECParameterSpec localECParameterSpec = sm2PriK.getParameters();        ECDomainParameters localECDomainParameters = new ECDomainParameters(localECParameterSpec.getCurve(),                localECParameterSpec.getG(), localECParameterSpec.getN());        ECPrivateKeyParameters localECPrivateKeyParameters = new ECPrivateKeyParameters(sm2PriK.getD(),                localECDomainParameters);        localSM2Engine.init(false, localECPrivateKeyParameters);        byte[] arrayOfByte3;        try {             arrayOfByte3 = localSM2Engine.processBlock(encodeData, 0, encodeData.length);        } catch (InvalidCipherTextException e) {            LOGGER.error("Decryption exception",e);            return null;        }
        return new String(arrayOfByte3);    }
    @Override    public String generateKey(String keySrc) {        return null;    }
    public static void main(String[] args) throws NoSuchAlgorithmException {
        /*        Encryption and decryption process: 1. Generate key pair: public key and private key         2. Encrypt using original text + public key         3. Decrypt using ciphertext + private key         */        IAlgorithm algo = new SM2();        String data = "tttttttsadf Steve Rogers agency fee screw liberated is 2222222222222222222";        String keySrc = "key2342423";        String[] keyPair = algo.generateKeyPair(keySrc);        System.err.println("keySrc:" + keySrc);        System.err.println("Public Key:" + keyPair[0]);        System.err.println("Private Key:" + keyPair[1]);        String ciphertext = algo.encrypt(data,keyPair[0]);        System.err.println("Encrypted ciphertext length:" + ciphertext.length() + ", ciphertext:" + ciphertext);        String deStr = algo.decrypt(ciphertext,keyPair[1]);        System.err.println("Decrypted plaintext:" + deStr);    }}

SM3

SM3:

package com.xy.util;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/** * @ClassName SM3 * @Description  SM3 encryption tool, hash algorithm to replace MD5, SHA-1, SHA-2 * @Author xy * @Version 1.0 **/public class SM3 implements  IAlgorithm{    private static final String ENCODING = "UTF-8";    private static final Logger LOGGER = LoggerFactory.getLogger(SM3.class);
    /**     * Encrypt using key     * @explain Specify key for encryption     * @param key Key     * @param srcData Byte array to be encrypted     * @return     */    public static byte[] hmac(byte[] key, byte[] srcData) {        KeyParameter keyParameter = new KeyParameter(key);        SM3Digest digest = new SM3Digest();        HMac mac = new HMac(digest);        mac.init(keyParameter);        mac.update(srcData, 0, srcData.length);        byte[] result = new byte[mac.getMacSize()];        mac.doFinal(result, 0);        return result;    }
    @Override    public String encrypt(String data, String key) {        // Convert the returned hash value to hexadecimal string        String resultHexString = "";        try {            // Convert string to byte array            byte[] srcData = data.getBytes(ENCODING);            // Call hash()            byte[] resultHash = hmac(key.getBytes(ENCODING),srcData);            // Convert the returned hash value to hexadecimal string            resultHexString = ByteUtils.toHexString(resultHash);        } catch (UnsupportedEncodingException e) {            LOGGER.error("Encryption exception",e);        }        return resultHexString;    }
    @Override    public String decrypt(String data, String key) {        return null;    }
    @Override    public String generateKey(String key) {        return null;    }
    @Override    public String[] generateKeyPair(String key) {        return new String[0];    }
    /**     * Check if the source data matches the encrypted data     * @explain Verify whether the original array and the generated hash array are the same array, validating whether the two are the same data     * @param srcStr Original string     * @param keyStr Key string     * @param sm3HexString Hexadecimal string     * @return Verification result     */    public static boolean verify(String srcStr,String keyStr, String sm3HexString) {        boolean flag = false;        try {            byte[] srcData = srcStr.getBytes(ENCODING);            byte[] keyData = keyStr.getBytes(ENCODING);            byte[] sm3Hash = ByteUtils.fromHexString(sm3HexString);            byte[] newHash = hmac(keyData,srcData);            if (Arrays.equals(newHash, sm3Hash)){                flag = true;            }        } catch (UnsupportedEncodingException e) {            LOGGER.error("Verify SM3 encryption result exception",e);
        }        return flag;    }
    public static void main(String[] args) {        IAlgorithm algo = new SM3();        String data = "Ah la la la la la la la la la la la la la la la la la la is brushing 2234sss";        String key = "key3453432";        String hex = algo.encrypt(data,key);        System.out.println("Parameter:" + data);        System.out.println("Ciphertext:" + hex);//        boolean verify = algo.verify(data,key, hex);//        System.out.println("Verification result:" + verify);    }}

SM4

SM4:

package com.xy.util;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;
/** * @ClassName SM4 * @Description National secret SM4 block cipher algorithm utility class (symmetric encryption) * @Author xy * @Version 1.0 **/public class SM4 implements  IAlgorithm{    private static final String ALGORITHM = "SM4";    private static final String ALGORITHM_ECB_PKCS5PADDING = "SM4/ECB/PKCS5Padding";    private static final String CHARSET_UTF8 = "utf-8";    /**     * SM4 algorithm currently only supports 128 bits (i.e., 16 bytes key)     */    private static final int DEFAULT_KEY_SIZE = 128;    private static final Logger LOGGER = LoggerFactory.getLogger(SM4.class);
    static {        // Prevent multiple instances of BouncyCastleProvider in memory        if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {            Security.addProvider(new BouncyCastleProvider());        }    }
    private static  SecretKey strKeyToSecretKey(String strKey){        byte[] bytes = Base64.getDecoder().decode(strKey);        SecretKeySpec secretKey = new SecretKeySpec(bytes, ALGORITHM);        return secretKey;    }
    private static byte[] encryptMode(SecretKey desKey,byte[] src,int mode) throws NoSuchPaddingException,            NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchProviderException {        //Encrypt        Cipher c = Cipher.getInstance(ALGORITHM_ECB_PKCS5PADDING, BouncyCastleProvider.PROVIDER_NAME);        c.init(mode, desKey);        byte[] enc = c.doFinal(src);        return enc;    }
    @Override    public String encrypt(String data, String key) {        try{            SecretKey secretKey = strKeyToSecretKey(key);            byte[] src = data.getBytes(CHARSET_UTF8);            return Base64.getEncoder().encodeToString(encryptMode(secretKey,src,Cipher.ENCRYPT_MODE));        }catch(Exception e){            LOGGER.error("Encryption exception",e);        }        return data;    }
    @Override    public String decrypt(String ciphertext, String key) {        SecretKey secretKey = strKeyToSecretKey(key);        byte[] mw = Base64.getDecoder().decode(ciphertext);        try{            return new String(encryptMode(secretKey,mw,Cipher.DECRYPT_MODE),CHARSET_UTF8);        }catch(Exception e){            LOGGER.error("Decryption exception",e);        }        return ciphertext;    }
    @Override    public String generateKey(String keySrc) {        try{            if(keySrc==null || keySrc.isEmpty()){                keySrc = String.valueOf(System.currentTimeMillis());            }            KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM, BouncyCastleProvider.PROVIDER_NAME);            SecureRandom random = new SecureRandom(keySrc.getBytes(CHARSET_UTF8));            keyGen.init(DEFAULT_KEY_SIZE,random);            SecretKey secretKey = keyGen.generateKey();            return Base64.getEncoder().encodeToString(secretKey.getEncoded());        }catch(Exception e){            LOGGER.error("Key generation exception",e);        }        return keySrc;    }
    @Override    public String[] generateKeyPair(String key) {        return new String[0];    }
    public static void main(String[] args) {        IAlgorithm algo = new SM4();        String data = "gggggggggggasd third party is top top top top top top top top top top top top top top top";        String keySrc = "key34324";        String keyGenerate = algo.generateKey(keySrc);        System.err.println("Key:" + keyGenerate);        String ciphertext = algo.encrypt(data,keyGenerate);        System.err.println("Ciphertext:" + ciphertext);        String deStr = algo.decrypt(ciphertext,keyGenerate);        System.err.println("Decrypted plaintext:" + deStr);    }}
Recommended in the past • Learn about artificial intelligence AI, large models, AI large models, ChatGPT, GPT-4, OpenAI, Claude 3... • Spring Boot 2.x "is about to exit the stage of history", how many more years can Java 8 hold on? • Netizens: Vue3 looks more like a haphazard patchwork, using it is to follow the trend, afraid of being said to be outdated • Netizens: My lazy colleague resigned, it's harder than breaking up, I cried for an hour

If you feel it’s not enough, here is a collection I organized, containing many good articles for everyone to consume!

Wonderful Collection
Spring/Spring Boot… Big Collection (16)
Database Collection (14)
MyBatis, MyBatis-Plus Collection (13)
Multithreading/Concurrency Collection (14)
Java Collection (including common functions) (34)
Middleware Collection (8)
Development tools, version management, release tools, etc. Collection (6)
Implementation of Cryptographic Algorithms: AES, 3DES, RSA, SM2, SM3, SM4
If you like it, please help with a one-click triple connection: “Like,Follow,Collect“, This is my creative motivation, thank you for your support. In the future, I will continue to output and strive to provide more excellent articles and the most practical dry goods.
Click “Looking” to support

Leave a Comment