SM2数字签名算法java实现

给出我的SM2数字签名算法代码Java实现,所属文件SM2Signer.java

@Override
public BigInteger[] generateSignature(byte[] message) {
    ECDomainParameters ec = key.getParameters();
    BigInteger n = ec.getN(); //阶n
    ECPoint G = ec.getG();    //基点G
    BigInteger r, s;
    // 获取私钥d
    BigInteger d = ((ECPrivateKeyParameters)key).getD();

    ECMultiplier basePointMultiplier = createBasePointMultiplier();
    // 初始化随机数生成器
    if (kCalculator.isDeterministic()) {
        kCalculator.init(n, d, message);
    } else {
        kCalculator.init(n, random);
    }

    do { // 计算s
        BigInteger k;
        BigInteger e;
        BigInteger tmp;
        BigInteger tmp2;
        do { // 计算r,参照GM/T 0003.2-2012 6.1
            k = kCalculator.nextK();

            ECPoint p = basePointMultiplier.multiply(G, k).normalize();

            e = org.bouncycastle.util.BigIntegers.fromUnsignedByteArray(message);
            // r = (e + x) mod n
            r = p.getAffineXCoord().toBigInteger().add(e).mod(n);

        } while (r.equals(ZERO) || r.add(k).equals(n));

        // tmp = (1+d).inverse
        tmp = d.add(ONE).modInverse(n);
        // tmp2 = k - r*d
        tmp2 = k.subtract(r.multiply(d));
        s = tmp.multiply(tmp2).mod(n);

    } while (s.equals(ZERO));

    return new BigInteger[] {r,s};
}

你可能感兴趣的:(bouncycastle)