rsa.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package public
  2. import (
  3. "bytes"
  4. "crypto/rsa"
  5. "errors"
  6. "io"
  7. )
  8. // 支持rsa公钥加密私钥解密;
  9. // 支持rsa公钥解密私钥加密。
  10. var RSA = &RSASecurity{}
  11. type RSASecurity struct {
  12. pubStr string // 公钥字符串
  13. priStr string // 私钥字符串
  14. pubkey *rsa.PublicKey // 公钥
  15. prikey *rsa.PrivateKey // 私钥
  16. }
  17. // 设置公钥
  18. func (rsas *RSASecurity) SetPublicKey(pubStr string) (err error) {
  19. rsas.pubStr = pubStr
  20. rsas.pubkey, err = rsas.GetPublickey()
  21. return err
  22. }
  23. // 设置私钥
  24. func (rsas *RSASecurity) SetPrivateKey(priStr string) (err error) {
  25. rsas.priStr = priStr
  26. rsas.prikey, err = rsas.GetPrivatekey()
  27. return err
  28. }
  29. // *rsa.PublicKey
  30. func (rsas *RSASecurity) GetPrivatekey() (*rsa.PrivateKey, error) {
  31. return getPriKey([]byte(rsas.priStr))
  32. }
  33. // *rsa.PrivateKey
  34. func (rsas *RSASecurity) GetPublickey() (*rsa.PublicKey, error) {
  35. return getPubKey([]byte(rsas.pubStr))
  36. }
  37. // 公钥加密
  38. func (rsas *RSASecurity) PubKeyENCTYPT(input []byte) ([]byte, error) {
  39. if rsas.pubkey == nil {
  40. return []byte(""), errors.New(`Please set the public key in advance`)
  41. }
  42. output := bytes.NewBuffer(nil)
  43. err := pubKeyIO(rsas.pubkey, bytes.NewReader(input), output, true)
  44. if err != nil {
  45. return []byte(""), err
  46. }
  47. return io.ReadAll(output)
  48. }
  49. // 公钥解密
  50. func (rsas *RSASecurity) PubKeyDECRYPT(input []byte) ([]byte, error) {
  51. if rsas.pubkey == nil {
  52. return []byte(""), errors.New(`Please set the public key in advance`)
  53. }
  54. output := bytes.NewBuffer(nil)
  55. err := pubKeyIO(rsas.pubkey, bytes.NewReader(input), output, false)
  56. if err != nil {
  57. return []byte(""), err
  58. }
  59. return io.ReadAll(output)
  60. }
  61. // 私钥加密
  62. func (rsas *RSASecurity) PriKeyENCTYPT(input []byte) ([]byte, error) {
  63. if rsas.prikey == nil {
  64. return []byte(""), errors.New(`Please set the private key in advance`)
  65. }
  66. output := bytes.NewBuffer(nil)
  67. err := priKeyIO(rsas.prikey, bytes.NewReader(input), output, true)
  68. if err != nil {
  69. return []byte(""), err
  70. }
  71. return io.ReadAll(output)
  72. }
  73. // 私钥解密
  74. func (rsas *RSASecurity) PriKeyDECRYPT(input []byte) ([]byte, error) {
  75. if rsas.prikey == nil {
  76. return []byte(""), errors.New(`Please set the private key in advance`)
  77. }
  78. output := bytes.NewBuffer(nil)
  79. err := priKeyIO(rsas.prikey, bytes.NewReader(input), output, false)
  80. if err != nil {
  81. return []byte(""), err
  82. }
  83. return io.ReadAll(output)
  84. }