use of org.bouncycastle.crypto.signers.RandomDSAKCalculator in project PCNGateway-Java-SDK by BSNDA.
the class Sm2SignUtil method xuperSignature.
public static byte[] xuperSignature(String privateKeyStr, byte[] message) throws Exception {
PrivateKey privateKey = Sm2SignUtil.getPrivateKey(privateKeyStr.getBytes());
BCECPrivateKey ecPrivateKey = (BCECPrivateKey) privateKey;
X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
ECDomainParameters ec = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
// Order n
BigInteger n = ec.getN();
// Base point G
ECPoint G = ec.getG();
BigInteger r, s;
// Get private key d
BigInteger d = ecPrivateKey.getD();
ECMultiplier basePointMultiplier = createBasePointMultiplier();
DSAKCalculator kCalculator = new RandomDSAKCalculator();
// Initialize the random number generator
// if (kCalculator.isDeterministic()) {
// kCalculator.init(n, d, message);
// } else {
kCalculator.init(n, new SecureRandom());
do {
// Calculate s
BigInteger k;
BigInteger e;
BigInteger tmp;
BigInteger tmp2;
do {
// Calculate r,refers to 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));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DERSequenceGenerator seq = new DERSequenceGenerator(bos);
seq.addObject(new ASN1Integer(r));
seq.addObject(new ASN1Integer(s));
seq.close();
return bos.toByteArray();
}
use of org.bouncycastle.crypto.signers.RandomDSAKCalculator in project radixdlt by radixdlt.
the class BouncyCastleKeyHandler method sign.
@Override
public ECDSASignature sign(byte[] hash, byte[] privateKey, byte[] publicKey, boolean enforceLowS, boolean useDeterministicSignatures) {
var signer = new ECDSASigner(useDeterministicSignatures ? new HMacDSAKCalculator(new SHA256Digest()) : new RandomDSAKCalculator());
signer.init(true, new ECPrivateKeyParameters(new BigInteger(1, privateKey), domain));
var components = signer.generateSignature(hash);
var r = components[0];
var s = components[1];
if (enforceLowS) {
s = s.compareTo(this.halfCurveOrder) <= 0 ? s : curveOrder.subtract(s);
}
return ECDSASignature.create(r, s, ECKeyUtils.calculateV(r, s, publicKey, hash));
}
Aggregations