lpilp / phpsm2sm3sm4

php版本,支持国密SM2的签名算法,非对称加解密,SM3的hash, SM4的对称加解密
329 stars 77 forks source link

java代码生成的签名用php代码验签不通过 #77

Closed KingAckerman closed 5 months ago

KingAckerman commented 5 months ago

问题描述:java生成的签名使用java验签方法可以验签成功,php生成的签名使用php的验签方法可以验签成功。但是java的签名用php代码验签不通过,php生成的签名用java代码验签不通过。 ` //测试环境私钥 String privateKey= "NDVmNjg2YjM0YWFiNTljOGE5ZGI2MGFmMmUzNjkwNjMyZjUzNjg5ZDQ0YmY4NjYyNWJhODIyMTA0MjRjZGZhNw==";

String publicKey= "MDQxZGMzZTA4NTJhMTMwYmI0MTU4YWVlNWZjNDY1YzAxZDAxMjY2NTViZWM0OGE3ZGVhYTgyZjM5MGFiODllNWZmMzExZTliYjdhZjA2YWVmNWNjODZiMDYxYmRiMDdlZWIzYmYyNGNjNzliNTA1ZGI1NTgzZTk1MzJmYzMwMGU3ZQ==";

String plainText = "MDAxNzExMjgxMTIxMDEwMDEwMDE="; //生成签名 BCECPrivateKey bcecPrivateKey = SM2Utils.getPrivateKeyFromString(privateKey); String sign = sign(bcecPrivateKey, plainText); System.out.println("生成签名: "+sign);

java 运行结果: 生成签名: X+DFt+FBpZhR46xvMvBtc9PXatljtrzHwNkCp+Twa7+r7MrEQljNWjx3g1JoMe3YpxygSRXpx9I5HgdKYOgwSg== java代码验签结果:true

//----------------------------------------------- $sm2 = new RtSm2('base64'); $sign_data = "MDAxNzExMjgxMTIxMDEwMDEwMDE="; $userid = 'UwMDAwMjAwMDAwMDAwMDAxODciLAog'; $privateKey = base64_decode("NDVmNjg2YjM0YWFiNTljOGE5ZGI2MGFmMmUzNjkwNjMyZjUzNjg5ZDQ0YmY4NjYyNWJhODIyMTA0MjRjZGZhNw=="); $publicKey = base64_decode("MDQxZGMzZTA4NTJhMTMwYmI0MTU4YWVlNWZjNDY1YzAxZDAxMjY2NTViZWM0OGE3ZGVhYTgyZjM5MGFiODllNWZmMzExZTliYjdhZjA2YWVmNWNjODZiMDYxYmRiMDdlZWIzYmYyNGNjNzliNTA1ZGI1NTgzZTk1MzJmYzMwMGU3ZQ=="); $sign = $sm2->doSign( $sign_data, $privateKey, $userid); $res = $sm2->verifySign($sign_data,$sign,$publicKey,$userid);

php 运行结果: 生成签名:MEUCIAMocK+AcKGqQQ3dMZh4CtHkRsc81sNMgkMLyRXQjlQKAiEAqS3rpsOSk1Epx8lYLgFqdTldydgW/6VJrcAmqJV8xTY= php代码验签结果:true`

KingAckerman commented 5 months ago

package demo; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.gm.GMNamedCurves; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey; import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; import org.bouncycastle.jcajce.spec.SM2ParameterSpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.util.encoders.Hex; import java.io.; import java.math.BigInteger; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.; import java.util.Arrays; import java.util.Base64; public class SM2Utils { private static X9ECParameters x9ECParameters = GMNamedCurves.getByName("sm2p256v1");

private static ECParameterSpec ecParameterSpec = new ECParameterSpec(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN());

private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

static {
    if (Security.getProvider("BC") == null) {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }
}

public static String getPublicKeyString(KeyPair keyPair){
    BCECPublicKey bcecPublicKey = (BCECPublicKey) keyPair.getPublic();
    String publicKeyStr = Hex.toHexString(bcecPublicKey.getQ().getEncoded(false));
    String publicKeyStrBase64 = new String(Base64.getEncoder().encode(publicKeyStr.getBytes(DEFAULT_CHARSET)), DEFAULT_CHARSET);
    return publicKeyStrBase64;
}

public static String getPrivateKeyString(KeyPair keyPair){
    BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) keyPair.getPrivate();
    String privateKeyStr = Hex.toHexString(bcecPrivateKey.getD().toByteArray());
    String privateKeyBase64 = new String(Base64.getEncoder().encode(privateKeyStr.getBytes(DEFAULT_CHARSET)), DEFAULT_CHARSET);
    return privateKeyBase64;
}

public static BCECPublicKey getPublicKeyFromString(String publicKeyStrBase64) throws Exception{
    String publicKeyString = new String(Base64.getDecoder().decode(publicKeyStrBase64.getBytes(DEFAULT_CHARSET)), DEFAULT_CHARSET);
    byte[] publicKey = Hex.decode(publicKeyString);
    int SM2_KEY_LEN = 32;
    int offset = 1;
    BigInteger x = new BigInteger(1, Arrays.copyOfRange(publicKey, 0 + offset, SM2_KEY_LEN + offset));
    BigInteger y = new BigInteger(1, Arrays.copyOfRange(publicKey, SM2_KEY_LEN + offset, SM2_KEY_LEN * 2 + offset));
    ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(x9ECParameters.getCurve().createPoint(x, y), ecParameterSpec);
    return new BCECPublicKey("EC", ecPublicKeySpec, BouncyCastleProvider.CONFIGURATION);
}

public static BCECPrivateKey getPrivateKeyFromString(String privateKeyStrBase64) throws Exception{
    String privateKeyString = new String(Base64.getDecoder().decode(privateKeyStrBase64.getBytes(DEFAULT_CHARSET)), DEFAULT_CHARSET);
    byte[] privateKey = Hex.decode(privateKeyString);
    ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(1, privateKey), ecParameterSpec);
    return new BCECPrivateKey("EC", ecPrivateKeySpec, BouncyCastleProvider.CONFIGURATION);
}

/**
 *
 * @param msg
 * @param userId
 * @param privateKey
 * @return r||s,直接拼接byte数组的rs
 */
public static byte[] signSm3WithSm2(byte[] msg, byte[] userId, PrivateKey privateKey){
    return rsAsn1ToPlainByteArray(signSm3WithSm2Asn1Rs(msg, userId, privateKey));
}

/**
 *
 * @param msg
 * @param userId
 * @param privateKey
 * @return rs in <b>asn1 format</b>
 */
public static byte[] signSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, PrivateKey privateKey){
    try {
        SM2ParameterSpec parameterSpec = new SM2ParameterSpec(userId);
        Signature signer = Signature.getInstance("SM3withSM2", "BC");
        signer.setParameter(parameterSpec);

        signer.initSign(privateKey, new SecureRandom());
        signer.update(msg, 0, msg.length);
        byte[] sig = signer.sign();
        return sig;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

/**
 *
 * @param msg
 * @param userId
 * @param rs r||s,直接拼接byte数组的rs
 * @param publicKey
 * @return
 */
public static boolean verifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, PublicKey publicKey){
    return verifySm3WithSm2Asn1Rs(msg, userId, rsPlainByteArrayToAsn1(rs), publicKey);
}

/**
 *
 * @param msg
 * @param userId
 * @param rs in <b>asn1 format</b>
 * @param publicKey
 * @return
 */
public static boolean verifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] rs, PublicKey publicKey){
    try {
        SM2ParameterSpec parameterSpec = new SM2ParameterSpec(userId);
        Signature verifier = Signature.getInstance("SM3withSM2", "BC");
        verifier.setParameter(parameterSpec);
        verifier.initVerify(publicKey);
        verifier.update(msg, 0, msg.length);
        return verifier.verify(rs);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private final static int RS_LEN = 32;

private static byte[] bigIntToFixexLengthBytes(BigInteger rOrS){
    // for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
    // r and s are the result of mod n, so they should be less than n and have length<=32
    byte[] rs = rOrS.toByteArray();
    if(rs.length == RS_LEN) return rs;
    else if(rs.length == RS_LEN + 1 && rs[0] == 0) return Arrays.copyOfRange(rs, 1, RS_LEN + 1);
    else if(rs.length < RS_LEN) {
        byte[] result = new byte[RS_LEN];
        Arrays.fill(result, (byte)0);
        System.arraycopy(rs, 0, result, RS_LEN - rs.length, rs.length);
        return result;
    } else {
        throw new RuntimeException("err rs: " + Hex.toHexString(rs));
    }
}

/**
 * BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s
 * @param rsDer rs in asn1 format
 * @return sign result in plain byte array
 */
private static byte[] rsAsn1ToPlainByteArray(byte[] rsDer){
    ASN1Sequence seq = ASN1Sequence.getInstance(rsDer);
    byte[] r = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(0)).getValue());
    byte[] s = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(1)).getValue());
    byte[] result = new byte[RS_LEN * 2];
    System.arraycopy(r, 0, result, 0, r.length);
    System.arraycopy(s, 0, result, RS_LEN, s.length);
    return result;
}

/**
 * BC的SM3withSM2验签需要的rs是asn1格式的,这个方法将直接拼接r||s的字节数组转化成asn1格式
 * @param sign in plain byte array
 * @return rs result in asn1 format
 */
private static byte[] rsPlainByteArrayToAsn1(byte[] sign){
    if(sign.length != RS_LEN * 2) throw new RuntimeException("err rs. ");
    BigInteger r = new BigInteger(1, Arrays.copyOfRange(sign, 0, RS_LEN));
    BigInteger s = new BigInteger(1, Arrays.copyOfRange(sign, RS_LEN, RS_LEN * 2));
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(r));
    v.add(new ASN1Integer(s));
    try {
        return new DERSequence(v).getEncoded("DER");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

}

lpilp commented 5 months ago

你没有认真看 readme呢, 你的签名生成 的 r+s 的, 签名一般标准的是asn1(r,s)的,你转换下格式就行了,不过看你使用的java的BC库的,那个库是支持生成的是 asn1(r,s) 的,是否选用错了函数

KingAckerman commented 5 months ago

额,将r+s的签名转成asn1(r,s)的就验签通过了。惭愧,惭愧