Giter VIP home page Giter VIP logo

Comments (3)

KingAckerman avatar KingAckerman commented on August 14, 2024

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);
    }
}

}

from phpsm2sm3sm4.

lpilp avatar lpilp commented on August 14, 2024

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

from phpsm2sm3sm4.

KingAckerman avatar KingAckerman commented on August 14, 2024

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

from phpsm2sm3sm4.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.