信创改造也有一段时间了,这里记录和总结一些关于SM2算法的知识点。
1. pom.xml
<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.57</version></dependency>
或
<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.70</version></dependency>
由于BC包版本多种多样,且实现SM2算法的过程和结果并不相同。因此在引入bc包时,需要考虑bc包版本的问题,否则将出现包冲突或ClassNotFound的问题。
这里特别强调,特别是进行SDK开发时,需询问接入方使用的JDK版本(是否为openjdk),需询问接入方项目中是否存在bc包,并根据实际情况调整bc包版本与项目打包方案
2. SM2算法在不同BC包下的不同结果
注意,不同开发语言甚至不同的bc包版本,“使用SM2算法进行非对称加密的结果内容的排序是有区别的”(C1C3C2或是C1C2C3)但由于目前使用为对称加密方案加密报文的情况不多见,因此这里暂不展示SM2加解密逻辑注意,在不同开发语言甚至不同bc包版本,“实现的SM2签名验签算法的代码和结果是有区别的”这里主要展示bc1.57与bc1.60及以上版本的区别,其他版本的bc包签名方案可以参考
private static final String SM2_STD = "sm2p256v1";//SM2算法使用的向量值,Java默认为1234567812345678,C#默认为null(和java的默认值效果相同),修改向量值将对算法结果存在影响 private static final String SM2_PID = "1234567812345678";
bc1.57版本的SM2签名验签方法
//签名public static String sign(String content, String privateKey) {//待签名内容转为字节数组byte[] message = content.getBytes();//获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName(SM2_STD);//构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(), sm2ECParameters.getN());BigInteger privateKeyD = new BigInteger(privateKey, 16);ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD,domainParameters);//创建签名实例SM2Signer sm2Signer = new SM2Signer();//初始化签名实例,带上ID,国密的要求,ID默认值:1234567812345678try {sm2Signer.init(true, new ParametersWithID(new ParametersWithRandom(privateKeyParameters, SecureRandom.getInstance("SHA1PRNG")),Strings.toByteArray(SM2_PID)));} catch (NoSuchAlgorithmException e) {e.printStackTrace();}//生成签名,签名分为两部分r和s,分别对应索引0和1的数组BigInteger[] bigIntegers = sm2Signer.generateSignature(message);byte[] rBytes = modifyRSFixedBytes(bigIntegers[0].toByteArray());byte[] sBytes = modifyRSFixedBytes(bigIntegers[1].toByteArray());byte[] signBytes = ByteUtils.concatenate(rBytes, sBytes);return Hex.toHexString(signBytes);}
//验签 public static boolean verify(String content, String publicKey, String sign) {//待签名内容byte[] message = content.getBytes();byte[] signData = Hex.decode(sign);// 获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName(SM2_STD);// 构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(), sm2ECParameters.getN());//提取公钥点ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));// 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint,domainParameters);//获取签名BigInteger R = null;BigInteger S = null;byte[] rBy = new byte[33];System.arraycopy(signData, 0, rBy, 1, 32);rBy[0] = 0x00;byte[] sBy = new byte[33];System.arraycopy(signData, 32, sBy, 1, 32);sBy[0] = 0x00;R = new BigInteger(rBy);S = new BigInteger(sBy);//创建签名实例SM2Signer sm2Signer = new SM2Signer();ParametersWithID parametersWithID = new ParametersWithID(publicKeyParameters,Strings.toByteArray(SM2_PID));sm2Signer.init(false, parametersWithID);//验证签名结果boolean verify = sm2Signer.verifySignature(message, R, S);return verify;}
BC1.60+时,SM2签名验签方法
//签名public static String sign4Der(String privateKey, String content) throws CryptoException {//待签名内容转为字节数组byte[] message = content.getBytes();//获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");//构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(), sm2ECParameters.getN());BigInteger privateKeyD = new BigInteger(privateKey, 16);ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);//创建签名实例SM2Signer sm2Signer = new SM2Signer();//初始化签名实例,带上ID,国密的要求,ID默认值:1234567812345678try {sm2Signer.init(true, new ParametersWithID(new ParametersWithRandom(privateKeyParameters, SecureRandom.getInstance("SHA1PRNG")), Strings.toByteArray("1234567812345678")));} catch (NoSuchAlgorithmException e) {e.printStackTrace();}sm2Signer.update(message, 0, message.length);byte[] signBytes = sm2Signer.generateSignature();String sign = Hex.toHexString(signBytes);return sign;}
//验签public static boolean verify4Der(String content, String publicKey, String sign){//待签名内容byte[] message = Hex.decode(content);byte[] signData = Hex.decode(sign);// 获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");// 构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(),sm2ECParameters.getN());//提取公钥点ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));// 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);//创建签名实例SM2Signer sm2Signer = new SM2Signer();ParametersWithID parametersWithID = new ParametersWithID(publicKeyParameters, Strings.toByteArray("1234567812345678"));sm2Signer.init(false, parametersWithID);sm2Signer.update(message, 0, message.length);//验证签名结果boolean verify = sm2Signer.verifySignature(signData);return verify;}
细心的朋友们就可以发现,针对不同版本的bc包,我实现的签名验签方法的名称是不一样的(sign和sign4Der,verify和verify4Der)
而,网上有许多SM2算法的帖子里经常有这句注释
//生成签名,签名分为两部分r和s,分别对应索引0和1的数组
但这句注释下方并没有相关的代码,经常让人看得莫名其妙。
其实低版本的bc包和高版本的bc包实现SM2的过程和结果并不相同,甚至类org.bouncycastle.crypto.signers中的方法都不兼容。如果你把bc1.57的签名验签代码,CV到bc1.60+的项目中,会发现sign和verify方法编译不会通过(反过来也是一样的),这也是出现ClassNotFound异常的主要原因。
这是因为SM2算法的签名结果的确是 “分为两部分r和s”两部分,在bc1.57中,签名结果是64字节的纯r+s的字节流拼接
BigInteger[] bigIntegers = sm2Signer.generateSignature(message);byte[] rBytes = modifyRSFixedBytes(bigIntegers[0].toByteArray());byte[] sBytes = modifyRSFixedBytes(bigIntegers[1].toByteArray());byte[] signBytes = ByteUtils.concatenate(rBytes, sBytes);
而在bc1.60+的版本中,SM2的结果是r的der编码字节流与s的der编码字节流拼接的结果
即
sm2Signer.update(message, 0, message.length);byte[] signBytes = sm2Signer.generateSignature();
因此,只要实现了64字节的纯R+S字节流与DER编码字节流相互转换的方法,那么就可以实现不同bc包之间签名方法的兼容了。
3. SM2Utils类
我在bc1.70的基础上,实现了一个SM2Utils类,该类包含了SM2加解密方法,实现了sign/sign4Der与verify/verify4Der的代码,并提供了64位纯字节流与DER编码字节流相互转化的方法
import java.io.IOException;import java.math.BigInteger;import java.nio.charset.StandardCharsets;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.util.HashMap;import org.bouncycastle.asn1.*;import org.bouncycastle.asn1.gm.GMNamedCurves;import org.bouncycastle.asn1.x9.X9ECParameters;import org.bouncycastle.crypto.AsymmetricCipherKeyPair;import org.bouncycastle.crypto.CryptoException;import org.bouncycastle.crypto.InvalidCipherTextException;import org.bouncycastle.crypto.engines.SM2Engine;import org.bouncycastle.crypto.generators.ECKeyPairGenerator;import org.bouncycastle.crypto.params.ECDomainParameters;import org.bouncycastle.crypto.params.ECKeyGenerationParameters;import org.bouncycastle.crypto.params.ECPrivateKeyParameters;import org.bouncycastle.crypto.params.ECPublicKeyParameters;import org.bouncycastle.crypto.params.ParametersWithID;import org.bouncycastle.crypto.params.ParametersWithRandom;import org.bouncycastle.crypto.signers.SM2Signer;import org.bouncycastle.math.ec.ECPoint;import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;import org.bouncycastle.util.Strings;import org.bouncycastle.util.encoders.Base64;import org.bouncycastle.util.encoders.Hex;public class SM2Utils {private static final String SM2_STD = "sm2p256v1";private static final String SM2_PID = "1234567812345678";/** * SM2加密算法 * * @param publicKey 公钥 * @param data数据 * @return */public static String encrypt(String publicKey, String data) throws InvalidCipherTextException {// 获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName(SM2_STD);// 构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(), sm2ECParameters.getN());//提取公钥点ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));// 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint,domainParameters);SM2Engine sm2Engine = new SM2Engine();sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom()));byte[] arrayOfBytes = null;byte[] cipherDataByte = Base64.encode(data.getBytes(StandardCharsets.UTF_8));arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);return Hex.toHexString(arrayOfBytes);}/** * SM2解密算法 * * @param privateKey 私钥 * @param data 密文数据 * @return */public static String decrypt(String privateKey, String data) throws InvalidCipherTextException {//获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName(SM2_STD);//构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(), sm2ECParameters.getN());BigInteger privateKeyD = new BigInteger(privateKey, 16);ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD,domainParameters);SM2Engine sm2Engine = new SM2Engine();sm2Engine.init(false, privateKeyParameters);byte[] arrayOfBytes = null;byte[] cipherDataByte = Hex.decode(data);arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);return new String(Base64.decode(arrayOfBytes), StandardCharsets.UTF_8);}/** * 私钥签名 1.64 模拟 1.57 * @param privateKey私钥 * @param content 待签名内容 * @return */public static String sign(String content, String privateKey) {//待签名内容转为字节数组byte[] message = content.getBytes();//获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");//构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(), sm2ECParameters.getN());BigInteger privateKeyD = new BigInteger(privateKey, 16);ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);//创建签名实例SM2Signer sm2Signer = new SM2Signer();//初始化签名实例,带上ID,国密的要求,ID默认值:1234567812345678try {sm2Signer.init(true, new ParametersWithID(new ParametersWithRandom(privateKeyParameters, SecureRandom.getInstance("SHA1PRNG")), Strings.toByteArray("1234567812345678")));} catch (NoSuchAlgorithmException e) {e.printStackTrace();}sm2Signer.update(message, 0, message.length);//生成签名,签名分为两部分r和s,分别对应索引0和1的数组byte[] signBytes = new byte[0];try {signBytes = sm2Signer.generateSignature();} catch (CryptoException e) {throw new RuntimeException(e);}//startbc1.57版本中,signData是纯r+s字符串拼接,如果为了兼容低版本的bc包,则需要加这一句byte[] signData = decodeDERSM2Sign(domainParameters, signBytes);//endString sign = Hex.toHexString(signData);return sign;}/** * 私钥签名 DER * @param privateKey私钥 * @param content 待签名内容 * @return */public static String sign4Der(String privateKey, String content) throws CryptoException {//待签名内容转为字节数组byte[] message = content.getBytes();//获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");//构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(), sm2ECParameters.getN());BigInteger privateKeyD = new BigInteger(privateKey, 16);ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);//创建签名实例SM2Signer sm2Signer = new SM2Signer();//初始化签名实例,带上ID,国密的要求,ID默认值:1234567812345678try {sm2Signer.init(true, new ParametersWithID(new ParametersWithRandom(privateKeyParameters, SecureRandom.getInstance("SHA1PRNG")), Strings.toByteArray("1234567812345678")));} catch (NoSuchAlgorithmException e) {e.printStackTrace();}sm2Signer.update(message, 0, message.length);//生成签名,签名分为两部分r和s,分别对应索引0和1的数组byte[] signBytes = sm2Signer.generateSignature();String sign = Hex.toHexString(signBytes);return sign;}/** * 验证签名 * @param publicKey 公钥 * @param content 待签名内容 * @param sign签名值 * @return */public static boolean verify(String content, String publicKey, String sign){//待签名内容byte[] message = Hex.decode(Hex.toHexString(content.getBytes()));byte[] signData = Hex.decode(sign);try {signData = encodeSM2SignToDER(signData);} catch (IOException e) {throw new RuntimeException(e);}// 获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");// 构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(),sm2ECParameters.getN());//提取公钥点ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));// 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);//创建签名实例SM2Signer sm2Signer = new SM2Signer();ParametersWithID parametersWithID = new ParametersWithID(publicKeyParameters, Strings.toByteArray("1234567812345678"));sm2Signer.init(false, parametersWithID);sm2Signer.update(message, 0, message.length);//验证签名结果boolean verify = sm2Signer.verifySignature(signData);return verify;}/** * 验证签名 * @param publicKey 公钥 * @param content 待签名内容 * @param sign签名值 * @return */public static boolean verify4Der(String content, String publicKey, String sign){//待签名内容byte[] message = Hex.decode(content);byte[] signData = Hex.decode(sign);// 获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");// 构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(),sm2ECParameters.getN());//提取公钥点ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));// 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);//创建签名实例SM2Signer sm2Signer = new SM2Signer();ParametersWithID parametersWithID = new ParametersWithID(publicKeyParameters, Strings.toByteArray("1234567812345678"));sm2Signer.init(false, parametersWithID);sm2Signer.update(message, 0, message.length);//验证签名结果boolean verify = sm2Signer.verifySignature(signData);return verify;}/** * 把64字节的纯R+S字节流转换成DER编码字节流 * @param rawSign * @return * @throws IOException */public static byte[] encodeSM2SignToDER(byte[] rawSign) throws IOException {//要保证大数是正数BigInteger r = new BigInteger(1, extractBytes(rawSign, 0, 32));BigInteger s = new BigInteger(1, extractBytes(rawSign, 32, 32));ASN1EncodableVector v = new ASN1EncodableVector();v.add(new ASN1Integer(r));v.add(new ASN1Integer(s));return new DERSequence(v).getEncoded(ASN1Encoding.DER);}private static byte[] extractBytes(byte[] src, int offset, int length) {byte[] result = new byte[length];System.arraycopy(src, offset, result, 0, result.length);return result;}public static byte[] decodeDERSM2Sign(ECDomainParameters domainParams, byte[] derSign) {ASN1Sequence as = DERSequence.getInstance(derSign);byte[] rBytes = ((ASN1Integer) as.getObjectAt(0)).getValue().toByteArray();byte[] sBytes = ((ASN1Integer) as.getObjectAt(1)).getValue().toByteArray();//由于大数的补0规则,所以可能会出现33个字节的情况,要修正回32个字节rBytes = fixToCurveLengthBytes(domainParams, rBytes);sBytes = fixToCurveLengthBytes(domainParams, sBytes);byte[] rawSign = new byte[rBytes.length + sBytes.length];System.arraycopy(rBytes, 0, rawSign, 0, rBytes.length);System.arraycopy(sBytes, 0, rawSign, rBytes.length, sBytes.length);return rawSign;}private static byte[] fixToCurveLengthBytes(ECDomainParameters domainParams, byte[] src) {int curveLen = getCurveLength(domainParams);if (src.length == curveLen) {return src;}byte[] result = new byte[curveLen];if (src.length > curveLen) {System.arraycopy(src, src.length - result.length, result, 0, result.length);} else {System.arraycopy(src, 0, result, result.length - src.length, src.length);}return result;}public static int getCurveLength(ECDomainParameters domainParams) {return (domainParams.getCurve().getFieldSize() + 7) / 8;}/** * 将R或者S修正为固定字节数 * * @param rs * @return */private static byte[] modifyRSFixedBytes(byte[] rs) {int length = rs.length;int fixedLength = 32;byte[] result = new byte[fixedLength];if (length < 32) {System.arraycopy(rs, 0, result, fixedLength - length, length);} else {System.arraycopy(rs, length - fixedLength, result, 0, fixedLength);}return result;}/** * 生成SM2公私钥对 * * @return */public static AsymmetricCipherKeyPair generateKeyPair() throws NoSuchAlgorithmException {//获取一条SM2曲线参数X9ECParameters sm2ECParameters = GMNamedCurves.getByName(SM2_STD);//构造domain参数ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),sm2ECParameters.getG(), sm2ECParameters.getN());//创建密钥生成器ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();//初始化生成器,带上随机数keyPairGenerator.init(new ECKeyGenerationParameters(domainParameters, SecureRandom.getInstance("SHA1PRNG")));//生成密钥对AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.generateKeyPair();return asymmetricCipherKeyPair;}}
若使用的是bc1.57,也可以使用encodeSM2SignToDER与decodeDERSM2Sign方法对sign字符串进行转换,以实现兼容高版本bc包的目的
4.一些补充
在同一个项目需要引用不同的bc包,或出现bc包冲突时,非常不建议直接将冲突的包移除。也许冲突包移除后,当前业务联调顺利通过了,但你并不能保证之前的业务是否使用了被移除的bc包(不然你之前的bc包是为什么引进去的)。如果之前的业务使用了被移除的bc包,那么在执行该业务线时,很可能出现ClassNotFound的问题。
当然也可以使用maven-shade-plugin的打包方案,对bc包进行改名,以此实现同一个项目引入不同bc包的目的,但该方案仅适用于openjdk。由于oraclejdk会对bc包进行验签操作,使用改了名字的bc包是不会验签通过的,因此该方法需要在openjdk的环境中才能使用。(或者你改Security的配置也行,但是改生产的Security你需要自己承担风险)