signer.go 988 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package util
  2. import (
  3. "crypto"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "fmt"
  7. "hash"
  8. )
  9. // Signer struct
  10. type Signer struct {
  11. opts rsa.PSSOptions
  12. method crypto.Hash
  13. h hash.Hash
  14. }
  15. // NewSigner func
  16. func NewSigner() *Signer {
  17. hash := crypto.SHA256
  18. var opts rsa.PSSOptions
  19. opts.SaltLength = rsa.PSSSaltLengthAuto
  20. return &Signer{opts, hash, hash.New()}
  21. }
  22. func (signer *Signer) Write(p []byte) (n int, err error) {
  23. signer.h.Write(p)
  24. return
  25. }
  26. // WriteUint64 func
  27. func (signer *Signer) WriteUint64(v uint64) {
  28. signer.h.Write(Uint64ToBytes(v))
  29. }
  30. // Sign func
  31. func (signer *Signer) Sign(key *rsa.PrivateKey) []byte {
  32. if res, err := rsa.SignPSS(rand.Reader, key, signer.method, signer.h.Sum(nil), &signer.opts); err != nil {
  33. panic(err)
  34. } else {
  35. return res
  36. }
  37. }
  38. // Verify func
  39. func (signer *Signer) Verify(key *rsa.PublicKey, sum []byte) {
  40. if err := rsa.VerifyPSS(key, signer.method, signer.h.Sum(nil), sum, &signer.opts); err != nil {
  41. panic(fmt.Errorf("Verify failed"))
  42. }
  43. }