signer.go 1022 B

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