rsa.go 945 B

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