rsa.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package unionpay
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/pem"
  7. "errors"
  8. "io/ioutil"
  9. )
  10. // RSAEncrypt RSA 加密
  11. func RSAEncrypt(publicKey, src []byte) (data []byte, err error) {
  12. block, _ := pem.Decode(publicKey)
  13. if block == nil {
  14. err = errors.New(`public key error`)
  15. return
  16. }
  17. pubI, e := x509.ParsePKIXPublicKey(block.Bytes)
  18. if e != nil {
  19. err = e
  20. return
  21. }
  22. pub := pubI.(*rsa.PublicKey)
  23. data, err = rsa.EncryptPKCS1v15(rand.Reader, pub, src)
  24. return
  25. }
  26. // RSADecrypt RSA 解密
  27. func RSADecrypt(priveKey, ciphertext []byte) (data []byte, err error) {
  28. block, _ := pem.Decode(priveKey)
  29. if block == nil {
  30. err = errors.New(`priveKey key error`)
  31. return
  32. }
  33. priv, e := x509.ParsePKCS1PrivateKey(block.Bytes)
  34. if e != nil {
  35. err = e
  36. return
  37. }
  38. rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
  39. return
  40. }
  41. // GetCertificate 获取证书信息
  42. func GetCertificate(filename string) (cert *x509.Certificate, data []byte, err error) {
  43. data, err = ioutil.ReadFile(filename)
  44. if err != nil {
  45. return
  46. }
  47. block, _ := pem.Decode(data)
  48. if block == nil {
  49. err = errors.New(`pem Decode error`)
  50. return
  51. }
  52. cert, err = x509.ParseCertificate(block.Bytes)
  53. return
  54. }