rsa.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package util
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/pem"
  8. "errors"
  9. "fmt"
  10. )
  11. // RSADecrypt 数据解密
  12. func RSADecrypt(privateKey string, ciphertext []byte) ([]byte, error) {
  13. block, _ := pem.Decode([]byte(privateKey))
  14. if block == nil {
  15. return nil, errors.New("PrivateKey format error")
  16. }
  17. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  18. if err != nil {
  19. oldErr := err
  20. key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  21. if err != nil {
  22. return nil, fmt.Errorf("ParsePKCS1PrivateKey error: %s, ParsePKCS8PrivateKey error: %s", oldErr.Error(), err.Error())
  23. }
  24. switch t := key.(type) {
  25. case *rsa.PrivateKey:
  26. var ok bool
  27. if priv, ok = key.(*rsa.PrivateKey); !ok {
  28. return nil, fmt.Errorf(" ParsePKCS8PrivateKey error: Not supported privatekey format, should be *rsa.PrivateKey, got %T", t)
  29. }
  30. default:
  31. return nil, fmt.Errorf("ParsePKCS1PrivateKey error: %s, ParsePKCS8PrivateKey error: Not supported privatekey format, should be *rsa.PrivateKey, got %T", oldErr.Error(), t)
  32. }
  33. }
  34. return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
  35. }
  36. // RSADecryptBase64 Base64 解码后再次进行 RSA 解密
  37. func RSADecryptBase64(privateKey string, cryptoText string) ([]byte, error) {
  38. encryptedData, err := base64.StdEncoding.DecodeString(cryptoText)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return RSADecrypt(privateKey, encryptedData)
  43. }