SM2加密解密执行报 Invalid point encoding 0x5c
私钥前加00,密文前加04,公钥前加04 确实可以解决问题。内在原因?
解决方法一:
SM2加密数据 由C1,C2,C3组成 国密密文的正确排序是 C1+C3+C2
我们安全芯片SM2加密处理的密文顺序是 C1+C3+C2 而BC库加密出来的顺序是C1+C2+C3
我们安全在C1数据最前面没有04,而BC库加密出来的数据前面有04
BC库生成SM2公私钥对时 私钥的前面 偶尔会多加两个 00 而我们安全芯片 不支持 去掉00就可以
公钥的签名偶尔会多加04 而我们安全芯片 不支持 去掉04就可以
解决方法二:
通过hutool 包封装好的方法进行加解密
引入代码块
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.64</version>
</dependency>
<dependency> <groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.3</version>
</dependency>
sm2加密代码
//将已知密钥加载ECPrivateKeyParameters类
public static final String PUBLIC_KEY="****填写生成的公钥***";
public static final String PRIVATE_KEY="****填写生成的私钥***";
ECPrivateKeyParameters privateKeyParameters= BCUtil.toSm2Params(WorkFlowServiceImpl.PRIVATE_KEY);
String xhex= WorkFlowServiceImpl.PUBLIC_KEY.substring(0,64);
String yhex=WorkFlowServiceImpl.PUBLIC_KEY.substring(64,128);
ECPublicKeyParameters ecpub= BCUtil.toSm2Params(xhex,yhex);
//实例化sm2对象
SM2 sm2=new SM2(privateKeyParameters,ecpub);
sm2.usePlainEncoding();
//加密方式
sm2.setMode(SM2Engine.Mode.C1C2C3);
//sm2加密
String enStr=sm2.encryptHex(str, KeyType.PublicKey);