rsa.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. package encrypter
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "fmt"
  9. "reflect"
  10. "strings"
  11. msgpack "gopkg.in/vmihailenco/msgpack.v2"
  12. )
  13. // PrivateKey type
  14. type PrivateKey rsa.PrivateKey
  15. // PublicKey type
  16. type PublicKey rsa.PublicKey
  17. const (
  18. keySize = 2048
  19. decryptBlockSize = 256
  20. encryptBlockSize = 190
  21. )
  22. // NewPrivateKey func
  23. func NewPrivateKey() *PrivateKey {
  24. pk, err := rsa.GenerateKey(rand.Reader, keySize)
  25. if err != nil {
  26. panic(fmt.Errorf("Error create rsa.PrivateKey %v", err))
  27. }
  28. return (*PrivateKey)(pk)
  29. }
  30. // ParsePrivateKey func
  31. func ParsePrivateKey(raw []byte) *PrivateKey {
  32. k, err := x509.ParsePKCS1PrivateKey(raw)
  33. if err != nil {
  34. panic(fmt.Errorf("Error parse privateKey %v", err))
  35. }
  36. return (*PrivateKey)(k)
  37. }
  38. // ParsePrivateKeyString func
  39. func ParsePrivateKeyString(str string) (*PrivateKey, error) {
  40. raw, err := base64.RawURLEncoding.DecodeString(str)
  41. if err != nil {
  42. slog.Debugf("Error key decode %v", err)
  43. return nil, err
  44. }
  45. k, err := x509.ParsePKCS1PrivateKey(raw)
  46. if err != nil {
  47. slog.Debugf("Error parse key %v", err)
  48. return nil, err
  49. }
  50. return (*PrivateKey)(k), nil
  51. }
  52. // ParsePublicKey func
  53. func ParsePublicKey(raw []byte) *PublicKey {
  54. k, err := x509.ParsePKIXPublicKey(raw)
  55. if err != nil {
  56. panic(fmt.Errorf("Error parse privateKey %v", err))
  57. }
  58. if p, ok := k.(*rsa.PublicKey); ok {
  59. return (*PublicKey)(p)
  60. }
  61. panic(fmt.Errorf("Invalid type %s", reflect.TypeOf(k).String()))
  62. }
  63. // ParsePublicKeyString func
  64. func ParsePublicKeyString(str string) (*PublicKey, error) {
  65. raw, err := base64.RawURLEncoding.DecodeString(str)
  66. if err != nil {
  67. slog.Debugf("Error key decode %v", err)
  68. return nil, err
  69. }
  70. k, err := x509.ParsePKIXPublicKey(raw)
  71. if err != nil {
  72. slog.Debugf("Error parse key %v", err)
  73. return nil, err
  74. }
  75. if p, ok := k.(*rsa.PublicKey); ok {
  76. return (*PublicKey)(p), nil
  77. }
  78. err = fmt.Errorf("Invalid type %s", reflect.TypeOf(k).String())
  79. slog.Debugf("Error %v", err)
  80. return nil, err
  81. }
  82. var _ msgpack.CustomEncoder = (*PrivateKey)(nil)
  83. var _ msgpack.CustomDecoder = (*PrivateKey)(nil)
  84. // EncodeMsgpack func
  85. func (s *PrivateKey) EncodeMsgpack(enc *msgpack.Encoder) error {
  86. return enc.Encode(s.Raw())
  87. }
  88. // DecodeMsgpack func
  89. func (s *PrivateKey) DecodeMsgpack(dec *msgpack.Decoder) error {
  90. var raw []byte
  91. err := dec.Decode(&raw)
  92. if err != nil {
  93. slog.Warnf("PrivateKey.DecodeMsgpack decode str %v", err)
  94. return err
  95. }
  96. sk, err := x509.ParsePKCS1PrivateKey(raw)
  97. if err != nil {
  98. slog.Warnf("PrivateKey.DecodeMsgpack parse pkcs key %v", err)
  99. return err
  100. }
  101. s.PublicKey = sk.PublicKey
  102. s.D = sk.D
  103. s.Primes = sk.Primes
  104. s.Precomputed = sk.Precomputed
  105. return nil
  106. }
  107. // Decrypt func
  108. func (s *PrivateKey) Decrypt(crypt []byte) (plain []byte, err error) {
  109. for {
  110. if len(crypt) <= decryptBlockSize {
  111. bb, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, (*rsa.PrivateKey)(s), crypt, nil)
  112. if err != nil {
  113. return nil, err
  114. }
  115. return append(plain, bb...), err
  116. }
  117. bb, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, (*rsa.PrivateKey)(s), crypt[:decryptBlockSize], nil)
  118. if err != nil {
  119. return nil, err
  120. }
  121. plain = append(plain, bb...)
  122. crypt = crypt[decryptBlockSize:]
  123. }
  124. }
  125. // MarshalJSON func
  126. func (s *PrivateKey) MarshalJSON() ([]byte, error) {
  127. return []byte("\"" + base64.RawURLEncoding.EncodeToString(s.Raw()) + "\""), nil
  128. }
  129. // UnmarshalJSON func
  130. func (s *PrivateKey) UnmarshalJSON(b []byte) error {
  131. if b[0] != '"' && b[len(b)-1] != '"' {
  132. return fmt.Errorf("Invalid key")
  133. }
  134. skey := strings.Replace(string(b[1:len(b)-1]), "\\n", "", -1)
  135. bb, err := base64.RawURLEncoding.DecodeString(skey)
  136. if err != nil {
  137. return fmt.Errorf("Error parse privateKey %v [%s]", err, skey)
  138. }
  139. k, err := x509.ParsePKCS1PrivateKey(bb)
  140. if err != nil {
  141. return fmt.Errorf("Error parse privateKey %v [%s]", err, string(bb))
  142. }
  143. s.D = k.D
  144. s.E = k.E
  145. s.N = k.N
  146. s.Primes = k.Primes
  147. return ((*rsa.PrivateKey)(s)).Validate()
  148. }
  149. func (s *PrivateKey) String() string {
  150. bb := x509.MarshalPKCS1PrivateKey((*rsa.PrivateKey)(s))
  151. return base64.RawURLEncoding.EncodeToString(bb)
  152. }
  153. // Public func
  154. func (s *PrivateKey) Public() *PublicKey {
  155. rp := (*rsa.PrivateKey)(s).PublicKey
  156. return (*PublicKey)(&rp)
  157. }
  158. // EncryptKey func
  159. func (s *PrivateKey) EncryptKey(key *PublicKey) EncryptedPrivateKey {
  160. bb, err := key.Encrypt(s.Raw())
  161. if err != nil {
  162. panic(err)
  163. }
  164. return (EncryptedPrivateKey)(bb)
  165. }
  166. // Raw func
  167. func (s *PrivateKey) Raw() []byte {
  168. return x509.MarshalPKCS1PrivateKey((*rsa.PrivateKey)(s))
  169. }
  170. // Equal func
  171. func (s *PrivateKey) Equal(key *PrivateKey) bool {
  172. if key == nil {
  173. return s == nil
  174. }
  175. k1 := (*rsa.PrivateKey)(s)
  176. k2 := (*rsa.PrivateKey)(key)
  177. return k1.E == k2.E && k1.D.Cmp(k2.D) == 0 && k1.N.Cmp(k2.N) == 0
  178. }
  179. var _ msgpack.CustomEncoder = (*PublicKey)(nil)
  180. var _ msgpack.CustomDecoder = (*PublicKey)(nil)
  181. // EncodeMsgpack func
  182. func (s *PublicKey) EncodeMsgpack(enc *msgpack.Encoder) error {
  183. return enc.Encode(s.Raw())
  184. }
  185. // DecodeMsgpack func
  186. func (s *PublicKey) DecodeMsgpack(dec *msgpack.Decoder) error {
  187. var raw []byte
  188. err := dec.Decode(&raw)
  189. if err != nil {
  190. return err
  191. }
  192. sko, err := x509.ParsePKIXPublicKey(raw)
  193. if err != nil {
  194. return err
  195. }
  196. if sk, ok := sko.(*rsa.PublicKey); ok {
  197. s.N = sk.N
  198. s.E = sk.E
  199. return nil
  200. }
  201. return fmt.Errorf("Unkown type %s", reflect.TypeOf(sko))
  202. }
  203. // Encrypt func
  204. func (s *PublicKey) Encrypt(data []byte) (crypt []byte, err error) {
  205. for {
  206. if len(data) <= encryptBlockSize {
  207. bb, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, (*rsa.PublicKey)(s), data, nil)
  208. if err != nil {
  209. return nil, err
  210. }
  211. return append(crypt, bb...), err
  212. }
  213. bb, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, (*rsa.PublicKey)(s), data[:encryptBlockSize], nil)
  214. if err != nil {
  215. return nil, err
  216. }
  217. crypt = append(crypt, bb...)
  218. data = data[encryptBlockSize:]
  219. }
  220. }
  221. // MarshalJSON func
  222. func (s *PublicKey) MarshalJSON() ([]byte, error) {
  223. return []byte("\"" + base64.RawURLEncoding.EncodeToString(s.Raw()) + "\""), nil
  224. }
  225. // UnmarshalJSON func
  226. func (s *PublicKey) UnmarshalJSON(b []byte) error {
  227. if b[0] != '"' && b[len(b)-1] != '"' {
  228. return fmt.Errorf("Invalid key")
  229. }
  230. skey := strings.Replace(string(b[1:len(b)-1]), "\\n", "", -1)
  231. bb, err := base64.RawURLEncoding.DecodeString(skey)
  232. if err != nil {
  233. return fmt.Errorf("Error parse privateKey %v [%s]", err, skey)
  234. }
  235. k, err := x509.ParsePKIXPublicKey(bb)
  236. if err != nil {
  237. return fmt.Errorf("Error parse privateKey %v [%s]", err, string(bb))
  238. }
  239. if pk, ok := k.(*rsa.PublicKey); ok {
  240. s.E = pk.E
  241. s.N = pk.N
  242. return nil
  243. }
  244. return fmt.Errorf("Invalid type %s", reflect.TypeOf(k))
  245. }
  246. func (s *PublicKey) String() string {
  247. return base64.RawURLEncoding.EncodeToString(s.Raw())
  248. }
  249. // Raw func
  250. func (s *PublicKey) Raw() []byte {
  251. bb, err := x509.MarshalPKIXPublicKey((*rsa.PublicKey)(s))
  252. if err != nil {
  253. panic(err)
  254. }
  255. return bb
  256. }
  257. // Equal func
  258. func (s *PublicKey) Equal(key *PublicKey) bool {
  259. if key == nil {
  260. return s == nil
  261. }
  262. k1 := (*rsa.PublicKey)(s)
  263. k2 := (*rsa.PublicKey)(key)
  264. return k1.E == k2.E && k1.N.Cmp(k2.N) == 0
  265. }