rsa.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2019 autocareai.com. All rights reserved.
  2. // Use of this source code is governed by autocareai.com.
  3. package config
  4. import (
  5. "bytes"
  6. "crypto/rand"
  7. "crypto/rsa"
  8. "crypto/x509"
  9. "encoding/base64"
  10. "encoding/pem"
  11. "fmt"
  12. "net/url"
  13. )
  14. func Base64Encode(src []byte) []byte {
  15. return []byte(base64.StdEncoding.EncodeToString(src))
  16. }
  17. func Base64Decode(src []byte) ([]byte, error) {
  18. return base64.StdEncoding.DecodeString(string(src))
  19. }
  20. func split(buf []byte, lim int) [][]byte {
  21. var chunk []byte
  22. chunks := make([][]byte, 0, len(buf)/lim+1)
  23. for len(buf) >= lim {
  24. chunk, buf = buf[:lim], buf[lim:]
  25. chunks = append(chunks, chunk)
  26. }
  27. if len(buf) > 0 {
  28. chunks = append(chunks, buf[:len(buf)])
  29. }
  30. return chunks
  31. }
  32. func RasDescrpto(data, privateKey []byte) ([]byte, error) {
  33. var err error
  34. var block *pem.Block
  35. block, _ = pem.Decode(privateKey)
  36. if block == nil {
  37. return nil, fmt.Errorf("私钥错误")
  38. }
  39. prkI, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  40. if err != nil {
  41. return nil, fmt.Errorf("解析私钥错误")
  42. }
  43. pri := prkI.(*rsa.PrivateKey)
  44. partLen := pri.N.BitLen() / 8
  45. raw, err := Base64Decode(data)
  46. chunks := split([]byte(raw), partLen)
  47. buffer := bytes.NewBufferString("")
  48. for _, chunk := range chunks {
  49. decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, pri, chunk)
  50. if err != nil {
  51. return nil, err
  52. }
  53. buffer.Write(decrypted)
  54. }
  55. r, err := url.QueryUnescape(buffer.String())
  56. if err != nil {
  57. return nil, err
  58. }
  59. return []byte(r), err
  60. }
  61. func Base64RsaEncrypt(data, publicKey []byte) ([]byte, error) {
  62. var err error
  63. var block *pem.Block
  64. block, _ = pem.Decode(publicKey)
  65. if block == nil {
  66. return nil, fmt.Errorf("公钥错误")
  67. }
  68. prkI, err := x509.ParsePKIXPublicKey(block.Bytes)
  69. if err != nil {
  70. return nil, fmt.Errorf("解析公钥错误")
  71. }
  72. pub := prkI.(*rsa.PublicKey)
  73. partLen := pub.N.BitLen()/8 - 11
  74. chunks := split(data, partLen)
  75. buffer := bytes.NewBufferString("")
  76. for _, chunk := range chunks {
  77. bytes, err := rsa.EncryptPKCS1v15(rand.Reader, pub, chunk)
  78. if err != nil {
  79. return nil, err
  80. }
  81. buffer.Write(bytes)
  82. }
  83. cipherText := Base64Encode(buffer.Bytes())
  84. return cipherText, nil
  85. }