signature.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package signer
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/rand"
  6. "crypto/rsa"
  7. "encoding/base64"
  8. "encoding/binary"
  9. "encrypter"
  10. "hash"
  11. "time"
  12. msgpack "gopkg.in/vmihailenco/msgpack.v2"
  13. )
  14. // PrivateKey type
  15. type PrivateKey ecdsa.PrivateKey
  16. // PublicKey type
  17. type PublicKey ecdsa.PublicKey
  18. // Signature type
  19. type Signature []byte
  20. const sha256 = crypto.SHA256
  21. const ivSize = 8
  22. // Signer struct
  23. type Signer struct {
  24. hasher hash.Hash
  25. }
  26. // New func
  27. func New() *Signer {
  28. return &Signer{hasher: sha256.New()}
  29. }
  30. // Write func
  31. func (s *Signer) Write(data []byte) {
  32. s.hasher.Write(data)
  33. }
  34. // WriteTime func
  35. func (s *Signer) WriteTime(data *time.Time) {
  36. b := make([]byte, 8)
  37. binary.BigEndian.PutUint64(b, uint64(data.Unix()))
  38. s.hasher.Write(b)
  39. }
  40. // WritePack func
  41. func (s *Signer) WritePack(data interface{}) {
  42. raw, err := msgpack.Marshal(data)
  43. if err != nil {
  44. panic(err)
  45. }
  46. s.hasher.Write(raw)
  47. }
  48. // Reset func
  49. func (s *Signer) Reset() {
  50. s.hasher.Reset()
  51. }
  52. // Sign func
  53. func (s *Signer) Sign(key *encrypter.PrivateKey) Signature {
  54. sign, err := rsa.SignPKCS1v15(rand.Reader, (*rsa.PrivateKey)(key), sha256, s.hasher.Sum(nil))
  55. if err != nil {
  56. panic(err)
  57. }
  58. s.hasher.Reset()
  59. return (Signature)(sign)
  60. }
  61. // Verify func
  62. func (s *Signer) Verify(key *encrypter.PublicKey, signature Signature) error {
  63. err := rsa.VerifyPKCS1v15((*rsa.PublicKey)(key), sha256, s.hasher.Sum(nil), signature)
  64. s.hasher.Reset()
  65. return err
  66. }
  67. // SignWithIV func
  68. func (s *Signer) SignWithIV(key *encrypter.PrivateKey) (Signature, error) {
  69. iv := make([]byte, ivSize)
  70. _, err := rand.Read(iv)
  71. if err != nil {
  72. return nil, err
  73. }
  74. s.hasher.Write(iv)
  75. sign, err := rsa.SignPKCS1v15(rand.Reader, (*rsa.PrivateKey)(key), sha256, s.hasher.Sum(nil))
  76. s.hasher.Reset()
  77. return (Signature)(append(iv, sign...)), err
  78. }
  79. // VerifyWithIV func
  80. func (s *Signer) VerifyWithIV(key *encrypter.PublicKey, signature Signature) error {
  81. iv := signature[:ivSize]
  82. s.hasher.Write(iv)
  83. err := rsa.VerifyPKCS1v15((*rsa.PublicKey)(key), sha256, s.hasher.Sum(nil), signature[ivSize:])
  84. s.hasher.Reset()
  85. return err
  86. }
  87. // MarshalJSON func
  88. func (s *Signature) MarshalJSON() ([]byte, error) {
  89. return []byte("\"" + base64.RawURLEncoding.EncodeToString(([]byte)(*s)) + "\""), nil
  90. }