ID Verification部分介面服務支援在認證請求中使用SM2加密傳輸個人資訊(姓名、社會安全號碼碼)。您可以通過公開金鑰對認證請求中的個人資訊參數進行加密。本文介紹如何開啟SM2參數加密。
SM2公開金鑰
02cd77e007bdc86eeaf9a479ba7a2c22bc0a517ccb3a6975c3f94b4ac93347dea6Java語言樣本
添加Maven依賴
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.65</version>
</dependency>範例程式碼
重要
Cipher 為有狀態物件,非安全執行緒,禁止在多線程間共用同一執行個體。
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.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.util.Base64;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
public class SM2EncryptUtil {
private static final String publicKey = "02cd77e007bdc86eeaf9a479ba7a2c22bc0a517ccb3a6975c3f94b4ac93347dea6";
// 根據實際使用方式調整
private static final int maxPoolSize = 20;
private static final BlockingQueue<Cipher> pool = new LinkedBlockingDeque<>(maxPoolSize);
static {
try {
// 初始化池
for (int i = 0; i < maxPoolSize; i++) {
Cipher newCipher = createCipher();
pool.put(newCipher);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* SM2加密
* @param content2Encrypt 待加密的明文
* @return Base64編碼的密文
*/
public static String encrypt(String content2Encrypt) {
Cipher cipher = null;
try {
cipher = borrow();
return Base64.getEncoder().encodeToString(cipher.doFinal(content2Encrypt.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (cipher != null) {
release(cipher);
}
}
}
private static Cipher createCipher() throws Exception {
BouncyCastleProvider provider = new BouncyCastleProvider();
// 擷取SM2相關參數
X9ECParameters parameters = GMNamedCurves.getByName("sm2p256v1");
// 橢圓曲線參數規格
ECParameterSpec ecParameterSpec = new ECParameterSpec(parameters.getCurve(), parameters.getG(), parameters.getN(), parameters.getH());
// 將公開金鑰HEX字串轉換為橢圓曲線對應的點
ECPoint ecPoint = parameters.getCurve().decodePoint(Hex.decode(publicKey));
// 擷取橢圓曲線KEY產生器
KeyFactory keyFactory = KeyFactory.getInstance("EC", provider);
// 將橢圓曲線點轉為公開金鑰KEY對象
BCECPublicKey bcecPublicKey = (BCECPublicKey) keyFactory.generatePublic(new ECPublicKeySpec(ecPoint, ecParameterSpec));
// 擷取SM2加密器
Cipher cipher = Cipher.getInstance("SM2", provider);
// 初始化為加密模式
cipher.init(Cipher.ENCRYPT_MODE, bcecPublicKey);
return cipher;
}
private static Cipher borrow() throws InterruptedException {
// 線程會阻塞直到有可用的Cipher
return pool.take();
}
private static void release(Cipher cipher) {
// 避免重複添加
if (cipher != null && !pool.contains(cipher)) {
// 將Cipher放回池中
pool.offer(cipher);
}
}
}