encrypt_rsa.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. package xorm
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "encoding/pem"
  9. "errors"
  10. "io"
  11. "io/ioutil"
  12. "math/big"
  13. )
  14. const (
  15. RSA_PUBKEY_ENCRYPT_MODE = iota //公钥加密
  16. RSA_PUBKEY_DECRYPT_MODE //公钥解密
  17. RSA_PRIKEY_ENCRYPT_MODE //私钥加密
  18. RSA_PRIKEY_DECRYPT_MODE //私钥解密
  19. )
  20. type RsaEncrypt struct {
  21. PubKey string
  22. PriKey string
  23. pubkey *rsa.PublicKey
  24. prikey *rsa.PrivateKey
  25. EncryptMode int
  26. DecryptMode int
  27. }
  28. func (this *RsaEncrypt) Encrypt(strMesg string) ([]byte, error) {
  29. var inByte []byte
  30. var err error
  31. if this.EncryptMode == RSA_PUBKEY_ENCRYPT_MODE {
  32. this.pubkey, err = getPubKey([]byte(this.PubKey))
  33. if err != nil {
  34. return nil, err
  35. }
  36. }
  37. if this.EncryptMode == RSA_PRIKEY_ENCRYPT_MODE {
  38. this.prikey, err = getPriKey([]byte(this.PriKey))
  39. if err != nil {
  40. return nil, err
  41. }
  42. }
  43. inByte = []byte(strMesg)
  44. inByte, err = this.Byte(inByte, this.EncryptMode)
  45. if err != nil {
  46. return nil, err
  47. }
  48. return inByte, nil
  49. }
  50. func (this *RsaEncrypt) Decrypt(crypted []byte) (decrypted []byte, err error) {
  51. if this.DecryptMode == RSA_PUBKEY_DECRYPT_MODE {
  52. this.pubkey, err = getPubKey([]byte(this.PubKey))
  53. if err != nil {
  54. return nil, err
  55. }
  56. }
  57. if this.DecryptMode == RSA_PRIKEY_DECRYPT_MODE {
  58. this.prikey, err = getPriKey([]byte(this.PriKey))
  59. if err != nil {
  60. return nil, err
  61. }
  62. }
  63. decrypted, err = base64.StdEncoding.DecodeString(string(crypted))
  64. if err != nil {
  65. return nil, err
  66. }
  67. decrypted, err = this.Byte(decrypted, this.DecryptMode)
  68. if err != nil {
  69. return nil, err
  70. }
  71. return decrypted, nil
  72. }
  73. func (this *RsaEncrypt) Byte(in []byte, mode int) ([]byte, error) {
  74. out := bytes.NewBuffer(nil)
  75. err := this.IO(bytes.NewReader(in), out, mode)
  76. if err != nil {
  77. return nil, err
  78. }
  79. return ioutil.ReadAll(out)
  80. }
  81. func (this *RsaEncrypt) IO(in io.Reader, out io.Writer, mode int) error {
  82. switch mode {
  83. case RSA_PUBKEY_ENCRYPT_MODE:
  84. if key, err := this.getPubKey(); err != nil {
  85. return err
  86. } else {
  87. return pubKeyIO(key, in, out, true)
  88. }
  89. case RSA_PUBKEY_DECRYPT_MODE:
  90. if key, err := this.getPubKey(); err != nil {
  91. return err
  92. } else {
  93. return pubKeyIO(key, in, out, false)
  94. }
  95. case RSA_PRIKEY_ENCRYPT_MODE:
  96. if key, err := this.getPriKey(); err != nil {
  97. return err
  98. } else {
  99. return priKeyIO(key, in, out, true)
  100. }
  101. case RSA_PRIKEY_DECRYPT_MODE:
  102. if key, err := this.getPriKey(); err != nil {
  103. return err
  104. } else {
  105. return priKeyIO(key, in, out, false)
  106. }
  107. default:
  108. return errors.New("mode not found")
  109. }
  110. }
  111. func (this *RsaEncrypt) getPubKey() (*rsa.PublicKey, error) {
  112. if this.pubkey == nil {
  113. return nil, ErrPublicKey
  114. }
  115. return this.pubkey, nil
  116. }
  117. func (this *RsaEncrypt) getPriKey() (*rsa.PrivateKey, error) {
  118. if this.prikey == nil {
  119. return nil, ErrPrivateKey
  120. }
  121. return this.prikey, nil
  122. }
  123. //-----------------------------------------
  124. var (
  125. ErrDataToLarge = errors.New("message too long for RSA public key size")
  126. ErrDataLen = errors.New("data length error")
  127. ErrDataBroken = errors.New("data broken, first byte is not zero")
  128. ErrKeyPairDismatch = errors.New("data is not encrypted by the private key")
  129. ErrDecryption = errors.New("decryption error")
  130. ErrPublicKey = errors.New("get public key error")
  131. ErrPrivateKey = errors.New("get private key error")
  132. )
  133. /*公钥解密*/
  134. func pubKeyDecrypt(pub *rsa.PublicKey, data []byte) ([]byte, error) {
  135. k := (pub.N.BitLen() + 7) / 8
  136. if k != len(data) {
  137. return nil, ErrDataLen
  138. }
  139. m := new(big.Int).SetBytes(data)
  140. if m.Cmp(pub.N) > 0 {
  141. return nil, ErrDataToLarge
  142. }
  143. m.Exp(m, big.NewInt(int64(pub.E)), pub.N)
  144. d := leftPad(m.Bytes(), k)
  145. if d[0] != 0 {
  146. return nil, ErrDataBroken
  147. }
  148. if d[1] != 0 && d[1] != 1 {
  149. return nil, ErrKeyPairDismatch
  150. }
  151. var i = 2
  152. for ; i < len(d); i++ {
  153. if d[i] == 0 {
  154. break
  155. }
  156. }
  157. i++
  158. if i == len(d) {
  159. return nil, nil
  160. }
  161. return d[i:], nil
  162. }
  163. /*私钥加密*/
  164. func priKeyEncrypt(rand io.Reader, priv *rsa.PrivateKey, hashed []byte) ([]byte, error) {
  165. tLen := len(hashed)
  166. k := (priv.N.BitLen() + 7) / 8
  167. if k < tLen+11 {
  168. return nil, ErrDataLen
  169. }
  170. em := make([]byte, k)
  171. em[1] = 1
  172. for i := 2; i < k-tLen-1; i++ {
  173. em[i] = 0xff
  174. }
  175. copy(em[k-tLen:k], hashed)
  176. m := new(big.Int).SetBytes(em)
  177. c, err := decrypt(rand, priv, m)
  178. if err != nil {
  179. return nil, err
  180. }
  181. copyWithLeftPad(em, c.Bytes())
  182. return em, nil
  183. }
  184. /*公钥加密或解密Reader*/
  185. func pubKeyIO(pub *rsa.PublicKey, in io.Reader, out io.Writer, isEncrytp bool) error {
  186. k := (pub.N.BitLen() + 7) / 8
  187. if isEncrytp {
  188. k = k - 11
  189. }
  190. buf := make([]byte, k)
  191. var b []byte
  192. var err error
  193. size := 0
  194. for {
  195. size, err = in.Read(buf)
  196. if err != nil {
  197. if err == io.EOF {
  198. return nil
  199. }
  200. return err
  201. }
  202. if size < k {
  203. b = buf[:size]
  204. } else {
  205. b = buf
  206. }
  207. if isEncrytp {
  208. b, err = rsa.EncryptPKCS1v15(rand.Reader, pub, b)
  209. } else {
  210. b, err = pubKeyDecrypt(pub, b)
  211. }
  212. if err != nil {
  213. return err
  214. }
  215. if _, err = out.Write(b); err != nil {
  216. return err
  217. }
  218. }
  219. return nil
  220. }
  221. /*私钥加密或解密Reader*/
  222. func priKeyIO(pri *rsa.PrivateKey, r io.Reader, w io.Writer, isEncrytp bool) error {
  223. k := (pri.N.BitLen() + 7) / 8
  224. if isEncrytp {
  225. k = k - 11
  226. }
  227. buf := make([]byte, k)
  228. var err error
  229. var b []byte
  230. size := 0
  231. for {
  232. size, err = r.Read(buf)
  233. if err != nil {
  234. if err == io.EOF {
  235. return nil
  236. }
  237. return err
  238. }
  239. if size < k {
  240. b = buf[:size]
  241. } else {
  242. b = buf
  243. }
  244. if isEncrytp {
  245. b, err = priKeyEncrypt(rand.Reader, pri, b)
  246. } else {
  247. b, err = rsa.DecryptPKCS1v15(rand.Reader, pri, b)
  248. }
  249. if err != nil {
  250. return err
  251. }
  252. if _, err = w.Write(b); err != nil {
  253. return err
  254. }
  255. }
  256. return nil
  257. }
  258. /*公钥加密或解密byte*/
  259. func pubKeyByte(pub *rsa.PublicKey, in []byte, isEncrytp bool) ([]byte, error) {
  260. k := (pub.N.BitLen() + 7) / 8
  261. if isEncrytp {
  262. k = k - 11
  263. }
  264. if len(in) <= k {
  265. if isEncrytp {
  266. return rsa.EncryptPKCS1v15(rand.Reader, pub, in)
  267. } else {
  268. return pubKeyDecrypt(pub, in)
  269. }
  270. } else {
  271. iv := make([]byte, k)
  272. out := bytes.NewBuffer(iv)
  273. if err := pubKeyIO(pub, bytes.NewReader(in), out, isEncrytp); err != nil {
  274. return nil, err
  275. }
  276. return ioutil.ReadAll(out)
  277. }
  278. }
  279. /*私钥加密或解密byte*/
  280. func priKeyByte(pri *rsa.PrivateKey, in []byte, isEncrytp bool) ([]byte, error) {
  281. k := (pri.N.BitLen() + 7) / 8
  282. if isEncrytp {
  283. k = k - 11
  284. }
  285. if len(in) <= k {
  286. if isEncrytp {
  287. return priKeyEncrypt(rand.Reader, pri, in)
  288. } else {
  289. return rsa.DecryptPKCS1v15(rand.Reader, pri, in)
  290. }
  291. } else {
  292. iv := make([]byte, k)
  293. out := bytes.NewBuffer(iv)
  294. if err := priKeyIO(pri, bytes.NewReader(in), out, isEncrytp); err != nil {
  295. return nil, err
  296. }
  297. return ioutil.ReadAll(out)
  298. }
  299. }
  300. /*读取公钥*/
  301. func getPubKey(in []byte) (*rsa.PublicKey, error) {
  302. block, _ := pem.Decode(in)
  303. if block == nil {
  304. return nil, ErrPublicKey
  305. }
  306. pub, err := x509.ParsePKIXPublicKey(block.Bytes)
  307. if err != nil {
  308. return nil, err
  309. } else {
  310. return pub.(*rsa.PublicKey), err
  311. }
  312. }
  313. /*读取私钥*/
  314. func getPriKey(in []byte) (*rsa.PrivateKey, error) {
  315. block, _ := pem.Decode(in)
  316. if block == nil {
  317. return nil, ErrPrivateKey
  318. }
  319. pri, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  320. if err == nil {
  321. return pri, nil
  322. }
  323. pri2, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  324. if err != nil {
  325. return nil, err
  326. } else {
  327. return pri2.(*rsa.PrivateKey), nil
  328. }
  329. }
  330. /*从crypto/rsa复制 */
  331. var bigZero = big.NewInt(0)
  332. var bigOne = big.NewInt(1)
  333. /*从crypto/rsa复制 */
  334. func encrypt(c *big.Int, pub *rsa.PublicKey, m *big.Int) *big.Int {
  335. e := big.NewInt(int64(pub.E))
  336. c.Exp(m, e, pub.N)
  337. return c
  338. }
  339. /*从crypto/rsa复制 */
  340. func decrypt(random io.Reader, priv *rsa.PrivateKey, c *big.Int) (m *big.Int, err error) {
  341. if c.Cmp(priv.N) > 0 {
  342. err = ErrDecryption
  343. return
  344. }
  345. var ir *big.Int
  346. if random != nil {
  347. var r *big.Int
  348. for {
  349. r, err = rand.Int(random, priv.N)
  350. if err != nil {
  351. return
  352. }
  353. if r.Cmp(bigZero) == 0 {
  354. r = bigOne
  355. }
  356. var ok bool
  357. ir, ok = modInverse(r, priv.N)
  358. if ok {
  359. break
  360. }
  361. }
  362. bigE := big.NewInt(int64(priv.E))
  363. rpowe := new(big.Int).Exp(r, bigE, priv.N)
  364. cCopy := new(big.Int).Set(c)
  365. cCopy.Mul(cCopy, rpowe)
  366. cCopy.Mod(cCopy, priv.N)
  367. c = cCopy
  368. }
  369. if priv.Precomputed.Dp == nil {
  370. m = new(big.Int).Exp(c, priv.D, priv.N)
  371. } else {
  372. m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0])
  373. m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1])
  374. m.Sub(m, m2)
  375. if m.Sign() < 0 {
  376. m.Add(m, priv.Primes[0])
  377. }
  378. m.Mul(m, priv.Precomputed.Qinv)
  379. m.Mod(m, priv.Primes[0])
  380. m.Mul(m, priv.Primes[1])
  381. m.Add(m, m2)
  382. for i, values := range priv.Precomputed.CRTValues {
  383. prime := priv.Primes[2+i]
  384. m2.Exp(c, values.Exp, prime)
  385. m2.Sub(m2, m)
  386. m2.Mul(m2, values.Coeff)
  387. m2.Mod(m2, prime)
  388. if m2.Sign() < 0 {
  389. m2.Add(m2, prime)
  390. }
  391. m2.Mul(m2, values.R)
  392. m.Add(m, m2)
  393. }
  394. }
  395. if ir != nil {
  396. m.Mul(m, ir)
  397. m.Mod(m, priv.N)
  398. }
  399. return
  400. }
  401. /*从crypto/rsa复制 */
  402. func copyWithLeftPad(dest, src []byte) {
  403. numPaddingBytes := len(dest) - len(src)
  404. for i := 0; i < numPaddingBytes; i++ {
  405. dest[i] = 0
  406. }
  407. copy(dest[numPaddingBytes:], src)
  408. }
  409. /*从crypto/rsa复制 */
  410. func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) {
  411. _, err = io.ReadFull(rand, s)
  412. if err != nil {
  413. return
  414. }
  415. for i := 0; i < len(s); i++ {
  416. for s[i] == 0 {
  417. _, err = io.ReadFull(rand, s[i:i+1])
  418. if err != nil {
  419. return
  420. }
  421. s[i] ^= 0x42
  422. }
  423. }
  424. return
  425. }
  426. /*从crypto/rsa复制 */
  427. func leftPad(input []byte, size int) (out []byte) {
  428. n := len(input)
  429. if n > size {
  430. n = size
  431. }
  432. out = make([]byte, size)
  433. copy(out[len(out)-n:], input)
  434. return
  435. }
  436. /*从crypto/rsa复制 */
  437. func modInverse(a, n *big.Int) (ia *big.Int, ok bool) {
  438. g := new(big.Int)
  439. x := new(big.Int)
  440. y := new(big.Int)
  441. g.GCD(x, y, a, n)
  442. if g.Cmp(bigOne) != 0 {
  443. return
  444. }
  445. if x.Cmp(bigOne) < 0 {
  446. x.Add(x, n)
  447. }
  448. return x, true
  449. }