utils.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package sm2
  2. import (
  3. "encoding/asn1"
  4. "math/big"
  5. )
  6. func Decompress(a []byte) *PublicKey {
  7. var aa, xx, xx3 sm2P256FieldElement
  8. P256Sm2()
  9. x := new(big.Int).SetBytes(a[1:])
  10. curve := sm2P256
  11. sm2P256FromBig(&xx, x)
  12. sm2P256Square(&xx3, &xx) // x3 = x ^ 2
  13. sm2P256Mul(&xx3, &xx3, &xx) // x3 = x ^ 2 * x
  14. sm2P256Mul(&aa, &curve.a, &xx) // a = a * x
  15. sm2P256Add(&xx3, &xx3, &aa)
  16. sm2P256Add(&xx3, &xx3, &curve.b)
  17. y2 := sm2P256ToBig(&xx3)
  18. y := new(big.Int).ModSqrt(y2, sm2P256.P)
  19. if getLastBit(y)!= uint(a[0]) {
  20. y.Sub(sm2P256.P, y)
  21. }
  22. return &PublicKey{
  23. Curve: P256Sm2(),
  24. X: x,
  25. Y: y,
  26. }
  27. }
  28. func Compress(a *PublicKey) []byte {
  29. buf := []byte{}
  30. yp := getLastBit(a.Y)
  31. buf = append(buf, a.X.Bytes()...)
  32. if n := len(a.X.Bytes()); n < 32 {
  33. buf = append(zeroByteSlice()[:(32-n)], buf...)
  34. }
  35. buf = append([]byte{byte(yp)}, buf...)
  36. return buf
  37. }
  38. func SignDigitToSignData(r, s *big.Int) ([]byte, error) {
  39. return asn1.Marshal(sm2Signature{r, s})
  40. }
  41. func SignDataToSignDigit(sign []byte) (*big.Int, *big.Int, error) {
  42. var sm2Sign sm2Signature
  43. _, err := asn1.Unmarshal(sign, &sm2Sign)
  44. if err != nil {
  45. return nil, nil, err
  46. }
  47. return sm2Sign.R, sm2Sign.S, nil
  48. }