Parameter encryption
Updated at:
ID Verification for Financial Services supports SM2 encryption for personal information, such as names and ID card numbers, in authentication requests. You can use a public key to encrypt these parameters. This topic describes how to enable SM2 parameter encryption.
Public key
The following SM2 public key is used for facial recognition in ID Verification for Financial Services.
02cd77e007bdc86eeaf9a479ba7a2c22bc0a517ccb3a6975c3f94b4ac93347dea6Java 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();
// Obtain the SM2 parameters.
X9ECParameters parameters = GMNamedCurves.getByName("sm2p256v1");
// Define the 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 an elliptic curve point.
ECPoint ecPoint = parameters.getCurve().decodePoint(Hex.decode(publicKey));
// Obtain the elliptic curve key factory.
KeyFactory keyFactory = KeyFactory.getInstance("EC", provider);
// Convert the elliptic curve point into a public key object.
BCECPublicKey bcecPublicKey = (BCECPublicKey) keyFactory.generatePublic(new ECPublicKeySpec(ecPoint, ecParameterSpec));
// Obtain the SM2 cipher.
cipher = Cipher.getInstance("SM2", provider);
// Initialize the cipher for encryption.
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);
}
}
}Is this page helpful?