rsaEncDec.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package util
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "crypto/rsa"
  7. "crypto/x509"
  8. "encoding/base64"
  9. "encoding/pem"
  10. "errors"
  11. "fmt"
  12. "github.com/gogf/gf/v2/frame/g"
  13. "github.com/gogf/gf/v2/os/gctx"
  14. "github.com/gogf/gf/v2/util/gconv"
  15. "io"
  16. "log"
  17. "os"
  18. "time"
  19. )
  20. var (
  21. PublicKey *rsa.PublicKey
  22. PrivateKey *rsa.PrivateKey
  23. )
  24. func InitApiEncryptPrivatePublicKey() {
  25. // 读取私钥文件
  26. privateKeyBytes, err := os.ReadFile("./etc/rsa/apiEncrypt_private_key.pem")
  27. if err != nil {
  28. log.Println("无法读取私钥文件:", err)
  29. return
  30. }
  31. // 解码私钥
  32. privateKeyBlock, _ := pem.Decode(privateKeyBytes)
  33. if privateKeyBlock == nil || privateKeyBlock.Type != "PRIVATE KEY" {
  34. log.Println("私钥文件格式错误")
  35. return
  36. }
  37. // 解析私钥
  38. privateKeys, err := x509.ParsePKCS8PrivateKey(privateKeyBlock.Bytes)
  39. if err != nil {
  40. log.Println("私钥解析失败:", err)
  41. return
  42. }
  43. // 转换为RSA类型的私钥
  44. rsaPrivateKey, ok := privateKeys.(*rsa.PrivateKey)
  45. if !ok {
  46. fmt.Println("无法转换为RSA类型的私钥")
  47. return
  48. }
  49. PrivateKey = rsaPrivateKey
  50. // 读取公钥文件
  51. publicKeyBytes, err := os.ReadFile("./etc/rsa/apiEncrypt_public_key.pem")
  52. if err != nil {
  53. log.Println("无法读取公钥文件:", err)
  54. return
  55. }
  56. log.Println("读取公钥文件")
  57. // 解码公钥
  58. publicKeyBlock, _ := pem.Decode(publicKeyBytes)
  59. if publicKeyBlock == nil || publicKeyBlock.Type != "PUBLIC KEY" {
  60. log.Println("公钥文件格式错误", publicKeyBlock.Type)
  61. return
  62. }
  63. // 解析公钥
  64. publicKeyInterface, err := x509.ParsePKIXPublicKey(publicKeyBlock.Bytes)
  65. if err != nil {
  66. log.Println("公钥解析失败:", err.Error())
  67. return
  68. }
  69. // 转换为公钥类型
  70. rsaPublicKey, ok := publicKeyInterface.(*rsa.PublicKey)
  71. if !ok {
  72. log.Println("无法转换为公钥类型")
  73. return
  74. }
  75. PublicKey = rsaPublicKey
  76. log.Println("初始化公钥成功", PublicKey)
  77. }
  78. // JyAntiEncrypt 接口数据加密
  79. func JyAntiEncrypt(plaintext []byte) (out, PKeyStr string, err error) {
  80. if plaintext == nil {
  81. return
  82. }
  83. if PublicKey == nil {
  84. err = errors.New("无效公钥")
  85. return
  86. }
  87. var aseByte = func() (rBytes []byte) {
  88. aesEncDecKey := g.Cfg().MustGet(gctx.New(), "apiEncryptKey", "JyEncrypt").String()
  89. if len(aesEncDecKey) >= aes.BlockSize {
  90. return gconv.Bytes(aesEncDecKey[:aes.BlockSize])
  91. }
  92. return gconv.Bytes(fmt.Sprintf("%s%s", aesEncDecKey, time.Now().Format("20060102150405"))[:aes.BlockSize])
  93. }()
  94. if len(aseByte) == 0 {
  95. return
  96. }
  97. out, err = SymmetricEncrypt(plaintext, aseByte)
  98. if err != nil {
  99. return
  100. }
  101. //非对称加密
  102. var pKeyByte []byte
  103. pKeyByte, err = rsa.EncryptPKCS1v15(rand.Reader, PublicKey, aseByte)
  104. if err == nil {
  105. PKeyStr = base64.StdEncoding.EncodeToString(pKeyByte)
  106. }
  107. return
  108. }
  109. // SymmetricEncrypt 对称加密
  110. func SymmetricEncrypt(plaintext []byte, key []byte) (string, error) {
  111. block, err := aes.NewCipher(key)
  112. if err != nil {
  113. return "", err
  114. }
  115. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  116. iv := ciphertext[:aes.BlockSize]
  117. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  118. return "", err
  119. }
  120. stream := cipher.NewCTR(block, iv)
  121. stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
  122. return base64.StdEncoding.EncodeToString(ciphertext), nil
  123. }