xlcetc / cryptogm

An implement of china crypto standards, including sm2,sm3 ,sm4 and sm9 algorithms.
Other
38 stars 14 forks source link

Generating new constants #7

Closed pat721 closed 1 year ago

pat721 commented 1 year ago

Hello,

I'm trying to use another curve so I calculate new constants with genconsts.go but the code for calculating s and sMinus1Over2 is missing. How can I calculate those constants?

Thanks.

triplewz commented 1 year ago
// s is the Montgomery encoding of the square root of -3. Then, s = sqrt(-3) * 2^256 mod p.
var s = &gfP{0x4c7a890d4bc5c1d4, 0xb5fb866e5e28fa49, 0xf201391aa72f97c1, 0x3cc0000000e137a5}

// sMinus1Over2 is the Montgomery encoding of (s-1)/2. Then, sMinus1Over2 = ( (s-1) / 2) * 2^256 mod p.
var sMinus1Over2 = &gfP{0x4c7a890d4bc5c1d4, 0xb5fb866e5e28fa49, 0xf201391aa72f97c1, 0x3cc0000000e137a5}

You can compute this in gfp filed.

triplewz commented 1 year ago

Actually, s is only used for computing hashToPoint, if you have no need for this, just ignore it.

pat721 commented 1 year ago

Actually, s is only used for computing hashToPoint, if you have no need for this, just ignore it.

This is actually exactly what I need.

// s is the Montgomery encoding of the square root of -3. Then, s = sqrt(-3) * 2^256 mod p.
var s = &gfP{0x4c7a890d4bc5c1d4, 0xb5fb866e5e28fa49, 0xf201391aa72f97c1, 0x3cc0000000e137a5}

// sMinus1Over2 is the Montgomery encoding of (s-1)/2. Then, sMinus1Over2 = ( (s-1) / 2) * 2^256 mod p.
var sMinus1Over2 = &gfP{0x4c7a890d4bc5c1d4, 0xb5fb866e5e28fa49, 0xf201391aa72f97c1, 0x3cc0000000e137a5}

You can compute this in gfp filed.

Could you be kind enough to provide me with an example? I already tried implementing it with the code given in the genconsts.go but failed to do so.

triplewz commented 1 year ago

The constant s should be wrong, sorry for that. You can refer the code bellowing:

func TestGens(t *testing.T) {
    // s is the Montgomery encoding of the square root of -3. Then, s = sqrt(-3) * 2^256 mod p.
    negThree := newGFp(-3)
    s := new(gfP)
    s.Sqrt(negThree)
    fmt.Println(s.String())
    // sMinus1Over2 is the Montgomery encoding of (s-1)/2. Then, sMinus1Over2 = ( (s-1) / 2) * 2^256 mod p.
    sMinus1Over2 := new(gfP)
    one := newGFp(1)
    gfpSub(sMinus1Over2, s, one)
    two := newGFp(2)
    inverse := new(gfP)
    inverse.Invert(two)
    gfpMul(sMinus1Over2, sMinus1Over2, inverse)
    fmt.Println(sMinus1Over2.String())
}

And the results :

8f4000000d3242b92e12588fcbc9e459a9bce0778466aa4b7b2e07c770965b71
22c0000007eaf4d5820b01efe0ac55cf65d7b9e14f70cc93b04ed177a9f3d077

Then just represent it as little-endian 64-bit words.

For hashToPoint, see this paper latincrypt12.pdf.

pat721 commented 1 year ago

Thank you very much! As this is exactly what I needed, I will close the issue.