Search code examples
c#bouncycastlesha256ecdsa

C# Sign Data with SHA-256withECDSA using BouncyCastle produce different Signature everytime


I am following this tutorial to sign data with SHA-256withECDSA.

Using the same private key and message, it generated different signature result every time. The only change I made is return Base64 encoded string instead of Base58

Is it supposed to be the same signature every time?

public static string GetSignature(string privateKey, string message)

{

    var curve = SecNamedCurves.GetByName("secp256k1");

    var domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
    var keyParameters = new

            BC.Crypto.Parameters.ECPrivateKeyParameters(new BC.Math.BigInteger(privateKey),

            domain);

    ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");

    signer.Init(true, keyParameters);

    signer.BlockUpdate(Encoding.ASCII.GetBytes(message), 0, Encoding.ASCII.GetBytes(message).Length);

    var signature = signer.GenerateSignature();

    return Convert.ToBase64String(signature);

}

Example result

MEQCIB0rqb8Dbrh+e2akoCVJaUS4tyJYqfRf8vdz/W2fUOomAiB3D2BaMYjwSgKRQyTd/W+YEn+wT0I4dq1hmgBfe/Sh7g==

MEUCIQDsWxG8Zr7MCemgGylAN+Y32qJYuDmqZMpaPwxTKosJ3AIgE3oSsBjcua/aCvfNXiMfcUM9U92p9aRlAIEopw/wvd0=

MEYCIQCjQ0EDHVFhASuUSPnCGjCb0O1sq3Op+aAl01afjIVviQIhAOnGyGN9cKswFn97de0o/Im9Hswo6AdnLhKIZSUcYbDY

MEYCIQCAqcHyhRcbLtuyimJ4XCHvJcz0p0Wd7FgJ1+07sOsC/gIhAKYwlhRv98C/3XeZE1TujkB9qMn2C99GaguJoWng9+2y

MEUCIQD7ObA0n0JpRNQDe+3udpeKGEk79KsrjHsjv/4Wlj2bigIgZERRSQBEN91HTJHqn+prlwSCKUT4AJx061Gi0tv8Xuw=

Solution

  • So the answer is: it should be non deterministic - everytime is different

    https://en.wikipedia.org/wiki/Nondeterministic_algorithm