rsa_crypto.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2021 Tencent Inc. All rights reserved.
  2. package utils
  3. import (
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "crypto/sha1"
  7. "crypto/x509"
  8. "encoding/base64"
  9. "fmt"
  10. )
  11. // EncryptOAEPWithPublicKey 使用公钥进行加密
  12. func EncryptOAEPWithPublicKey(message string, publicKey *rsa.PublicKey) (ciphertext string, err error) {
  13. if publicKey == nil {
  14. return "", fmt.Errorf("you should input *rsa.PublicKey")
  15. }
  16. ciphertextByte, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, publicKey, []byte(message), nil)
  17. if err != nil {
  18. return "", fmt.Errorf("encrypt message with public key err:%s", err.Error())
  19. }
  20. ciphertext = base64.StdEncoding.EncodeToString(ciphertextByte)
  21. return ciphertext, nil
  22. }
  23. // EncryptOAEPWithCertificate 先解析出证书中的公钥,然后使用公钥进行加密
  24. func EncryptOAEPWithCertificate(message string, certificate *x509.Certificate) (ciphertext string, err error) {
  25. if certificate == nil {
  26. return "", fmt.Errorf("you should input *x509.Certificate")
  27. }
  28. publicKey, ok := certificate.PublicKey.(*rsa.PublicKey)
  29. if !ok {
  30. return "", fmt.Errorf("certificate is invalid")
  31. }
  32. return EncryptOAEPWithPublicKey(message, publicKey)
  33. }
  34. // DecryptOAEP 使用私钥进行解密
  35. func DecryptOAEP(ciphertext string, privateKey *rsa.PrivateKey) (message string, err error) {
  36. if privateKey == nil {
  37. return "", fmt.Errorf("you should input *rsa.PrivateKey")
  38. }
  39. decodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)
  40. if err != nil {
  41. return "", fmt.Errorf("base64 decode failed, error=%s", err.Error())
  42. }
  43. messageBytes, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, privateKey, decodedCiphertext, nil)
  44. if err != nil {
  45. return "", fmt.Errorf("decrypt ciphertext with private key err:%s", err)
  46. }
  47. return string(messageBytes), nil
  48. }