Parameter encryption

更新时间:
复制 MD 格式

Some Identity Verification API services support SM2 encryption to transmit personal information, such as names and ID card numbers, in authentication requests. These parameters are encrypted using a public key. This topic describes how to enable SM2 parameter encryption.

SM2 public key

02cd77e007bdc86eeaf9a479ba7a2c22bc0a517ccb3a6975c3f94b4ac93347dea6

Java example

Add a Maven dependency

<dependency>
  <groupId>org.bouncycastle</groupId>
  <artifactId>bcprov-jdk15on</artifactId>
  <version>1.65</version>
</dependency>

Sample code

import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.util.Base64;

public class SM2EncryptUtils {

    private static final String publicKey = "02cd77e007bdc86eeaf9a479ba7a2c22bc0a517ccb3a6975c3f94b4ac93347dea6";

    private static Cipher cipher;

    static {
        try {
            BouncyCastleProvider provider = new BouncyCastleProvider();
            // Get SM2-related parameters.
            X9ECParameters parameters = GMNamedCurves.getByName("sm2p256v1");
            // Elliptic curve parameter specification.
            ECParameterSpec ecParameterSpec = new ECParameterSpec(parameters.getCurve(), parameters.getG(), parameters.getN(), parameters.getH());
            // Convert the public key from a HEX string to a point on the elliptic curve.
            ECPoint ecPoint = parameters.getCurve().decodePoint(Hex.decode(publicKey));
            // Get the elliptic curve key factory.
            KeyFactory keyFactory = KeyFactory.getInstance("EC", provider);
            // Convert the elliptic curve point to a public key object.
            BCECPublicKey bcecPublicKey = (BCECPublicKey) keyFactory.generatePublic(new ECPublicKeySpec(ecPoint, ecParameterSpec));
            // Get the SM2 cipher.
            cipher = Cipher.getInstance("SM2", provider);
            // Initialize for encryption mode.
            cipher.init(Cipher.ENCRYPT_MODE, bcecPublicKey);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * SM2 encryption
     * @param content The content to encrypt.
     * @return The encrypted ciphertext.
     */
    public static String encrypt(String content) {
        try {
            String contentEncrypt = Base64.getEncoder().encodeToString(cipher.doFinal(content.getBytes("UTF-8")));
            return contentEncrypt;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}