rsa.go 904 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package utils
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/pem"
  8. "fmt"
  9. )
  10. // 创建私钥
  11. var privateKey, _ = rsa.GenerateKey(rand.Reader, 2048)
  12. // 私钥解密
  13. func encryption(password string) string {
  14. encrypted, _ := base64.StdEncoding.DecodeString(password)
  15. decryptedText, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encrypted)
  16. if err != nil {
  17. fmt.Println("Failed to decrypt data:", err)
  18. return ""
  19. }
  20. return string(decryptedText)
  21. }
  22. // 返回公钥
  23. func returnPublicKey() string {
  24. publicKey := &privateKey.PublicKey
  25. publicKeyDer, err := x509.MarshalPKIXPublicKey(publicKey)
  26. if err != nil {
  27. fmt.Println("Failed to convert public key to DER format:", err)
  28. return ""
  29. }
  30. publicKeyPem := &pem.Block{
  31. Type: "PUBLIC KEY",
  32. Bytes: publicKeyDer,
  33. }
  34. publicKeyPemBytes := pem.EncodeToMemory(publicKeyPem)
  35. return string(publicKeyPemBytes)
  36. }