github.com/hellobchain/newcryptosm@v0.0.0-20221019060107-edb949a317e9/sm9/gfp.go (about)

     1  package sm9
     2  
     3  import "fmt"
     4  
     5  type gfP [4]uint64
     6  
     7  func newGFp(x int64) (out *gfP) {
     8  	if x >= 0 {
     9  		out = &gfP{uint64(x)}
    10  	} else {
    11  		out = &gfP{uint64(-x)}
    12  		gfpNeg(out, out)
    13  	}
    14  
    15  	montEncode(out, out)
    16  	return out
    17  }
    18  
    19  func (e *gfP) String() string {
    20  	return fmt.Sprintf("%16.16x%16.16x%16.16x%16.16x", e[3], e[2], e[1], e[0])
    21  }
    22  
    23  func (e *gfP) Set(f *gfP) {
    24  	e[0] = f[0]
    25  	e[1] = f[1]
    26  	e[2] = f[2]
    27  	e[3] = f[3]
    28  }
    29  
    30  func (e *gfP) Invert(f *gfP) {
    31  	//bits := [4]uint64{0x185cac6c5e089665, 0xee5b88d120b5b59e, 0xaa6fecb86184dc21, 0x8fb501e34aa387f9}
    32  	//p-2
    33  	bits := [4]uint64{0xe56f9b27e351457b, 0x21f2934b1a7aeedb, 0xd603ab4ff58ec745, 0xb640000002a3a6f1}
    34  
    35  	sum, power := &gfP{}, &gfP{}
    36  	sum.Set(rN1)
    37  	power.Set(f)
    38  
    39  	for word := 0; word < 4; word++ {
    40  		for bit := uint(0); bit < 64; bit++ {
    41  			if (bits[word]>>bit)&1 == 1 {
    42  				gfpMul(sum, sum, power)
    43  			}
    44  			gfpMul(power, power, power)
    45  		}
    46  	}
    47  
    48  	gfpMul(sum, sum, r3)
    49  	e.Set(sum)
    50  }
    51  
    52  func (e *gfP) Marshal(out []byte) {
    53  	for w := uint(0); w < 4; w++ {
    54  		for b := uint(0); b < 8; b++ {
    55  			out[8*w+b] = byte(e[3-w] >> (56 - 8*b))
    56  		}
    57  	}
    58  }
    59  func (e *gfP) Marshal_uint64(out [12]uint64) {
    60  	a := [4]uint64(*e)
    61  	for i := 0; i < 12; i++ {
    62  		out[i] = a[i]
    63  	}
    64  }
    65  
    66  func (e *gfP) Unmarshal(in []byte) {
    67  	for w := uint(0); w < 4; w++ {
    68  		for b := uint(0); b < 8; b++ {
    69  			e[3-w] += uint64(in[8*w+b]) << (56 - 8*b)
    70  		}
    71  	}
    72  }
    73  
    74  func montEncode(c, a *gfP) { gfpMul(c, a, r2) }
    75  func montDecode(c, a *gfP) { gfpMul(c, a, &gfP{1}) }