蛋蛋星球-客户端
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 

195 wiersze
4.5 KiB

  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "encoding/pem"
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "os"
  14. )
  15. // 生成私钥文件 TODO 未指定路径
  16. func RsaKeyGen(bits int) error {
  17. privateKey, err := rsa.GenerateKey(rand.Reader, bits)
  18. if err != nil {
  19. return err
  20. }
  21. derStream := x509.MarshalPKCS1PrivateKey(privateKey)
  22. block := &pem.Block{
  23. Type: "RSA PRIVATE KEY",
  24. Bytes: derStream,
  25. }
  26. priFile, err := os.Create("private.pem")
  27. if err != nil {
  28. return err
  29. }
  30. err = pem.Encode(priFile, block)
  31. priFile.Close()
  32. if err != nil {
  33. return err
  34. }
  35. // 生成公钥文件
  36. publicKey := &privateKey.PublicKey
  37. derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
  38. if err != nil {
  39. return err
  40. }
  41. block = &pem.Block{
  42. Type: "PUBLIC KEY",
  43. Bytes: derPkix,
  44. }
  45. pubFile, err := os.Create("public.pem")
  46. if err != nil {
  47. return err
  48. }
  49. err = pem.Encode(pubFile, block)
  50. pubFile.Close()
  51. if err != nil {
  52. return err
  53. }
  54. return nil
  55. }
  56. // 生成私钥文件, 返回 privateKey , publicKey, error
  57. func RsaKeyGenText(bits int) (string, string, error) { // bits 字节位 1024/2048
  58. privateKey, err := rsa.GenerateKey(rand.Reader, bits)
  59. if err != nil {
  60. return "", "", err
  61. }
  62. derStream := x509.MarshalPKCS1PrivateKey(privateKey)
  63. block := &pem.Block{
  64. Type: "RSA PRIVATE KEY",
  65. Bytes: derStream,
  66. }
  67. priBuff := bytes.NewBuffer(nil)
  68. err = pem.Encode(priBuff, block)
  69. if err != nil {
  70. return "", "", err
  71. }
  72. // 生成公钥文件
  73. publicKey := &privateKey.PublicKey
  74. derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
  75. if err != nil {
  76. return "", "", err
  77. }
  78. block = &pem.Block{
  79. Type: "PUBLIC KEY",
  80. Bytes: derPkix,
  81. }
  82. pubBuff := bytes.NewBuffer(nil)
  83. err = pem.Encode(pubBuff, block)
  84. if err != nil {
  85. return "", "", err
  86. }
  87. return priBuff.String(), pubBuff.String(), nil
  88. }
  89. // 加密
  90. func RsaEncrypt(rawData, publicKey []byte) ([]byte, error) {
  91. block, _ := pem.Decode(publicKey)
  92. if block == nil {
  93. return nil, errors.New("public key error")
  94. }
  95. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  96. if err != nil {
  97. return nil, err
  98. }
  99. pub := pubInterface.(*rsa.PublicKey)
  100. return rsa.EncryptPKCS1v15(rand.Reader, pub, rawData)
  101. }
  102. // 公钥加密
  103. func RsaEncrypts(data, keyBytes []byte) []byte {
  104. //解密pem格式的公钥
  105. block, _ := pem.Decode(keyBytes)
  106. if block == nil {
  107. panic(errors.New("public key error"))
  108. }
  109. // 解析公钥
  110. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  111. if err != nil {
  112. panic(err)
  113. }
  114. // 类型断言
  115. pub := pubInterface.(*rsa.PublicKey)
  116. //加密
  117. ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pub, data)
  118. if err != nil {
  119. panic(err)
  120. }
  121. return ciphertext
  122. }
  123. // 解密
  124. func RsaDecrypt(cipherText, privateKey []byte) ([]byte, error) {
  125. block, _ := pem.Decode(privateKey)
  126. if block == nil {
  127. return nil, errors.New("private key error")
  128. }
  129. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  130. if err != nil {
  131. return nil, err
  132. }
  133. return rsa.DecryptPKCS1v15(rand.Reader, priv, cipherText)
  134. }
  135. // 从证书获取公钥
  136. func OpensslPemGetPublic(pathOrString string) (interface{}, error) {
  137. var certPem []byte
  138. var err error
  139. if IsFile(pathOrString) && Exists(pathOrString) {
  140. certPem, err = ioutil.ReadFile(pathOrString)
  141. if err != nil {
  142. return nil, err
  143. }
  144. if string(certPem) == "" {
  145. return nil, errors.New("empty pem file")
  146. }
  147. } else {
  148. if pathOrString == "" {
  149. return nil, errors.New("empty pem string")
  150. }
  151. certPem = StringToSlice(pathOrString)
  152. }
  153. block, rest := pem.Decode(certPem)
  154. if block == nil || block.Type != "PUBLIC KEY" {
  155. //log.Fatal("failed to decode PEM block containing public key")
  156. return nil, errors.New("failed to decode PEM block containing public key")
  157. }
  158. pub, err := x509.ParsePKIXPublicKey(block.Bytes)
  159. if err != nil {
  160. log.Fatal(err)
  161. }
  162. fmt.Printf("Got a %T, with remaining data: %q", pub, rest)
  163. return pub, nil
  164. }
  165. // StringToPrivateKey 字符串变为私钥
  166. func StringToPrivateKey(base64Str string) (*rsa.PrivateKey, error) {
  167. // Base64解码以获取DER数据
  168. derData, err := base64.StdEncoding.DecodeString(base64Str)
  169. if err != nil {
  170. return nil, fmt.Errorf("base64 decode failed: %v", err)
  171. }
  172. // 解析DER数据以获取私钥
  173. privateKey, err := x509.ParsePKCS8PrivateKey(derData)
  174. if err != nil {
  175. return nil, fmt.Errorf("failed to parse private key: %v", err)
  176. }
  177. // 类型断言以确保privateKey是*rsa.PrivateKey类型
  178. rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey)
  179. if !ok {
  180. return nil, fmt.Errorf("private key is not of type *rsa.PrivateKey")
  181. }
  182. return rsaPrivateKey, nil
  183. }