rsa.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package rsa
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/pem"
  8. )
  9. var _ Public = (*rsaPub)(nil)
  10. var _ Private = (*rsaPri)(nil)
  11. type Public interface {
  12. i()
  13. // Encrypt 加密
  14. Encrypt(encryptStr string) (string, error)
  15. }
  16. type Private interface {
  17. i()
  18. // Decrypt 解密
  19. Decrypt(decryptStr string) (string, error)
  20. }
  21. type rsaPub struct {
  22. PublicKey string
  23. }
  24. type rsaPri struct {
  25. PrivateKey string
  26. }
  27. func NewPublic(publicKey string) Public {
  28. return &rsaPub{
  29. PublicKey: publicKey,
  30. }
  31. }
  32. func NewPrivate(privateKey string) Private {
  33. return &rsaPri{
  34. PrivateKey: privateKey,
  35. }
  36. }
  37. func (pub *rsaPub) i() {}
  38. func (pub *rsaPub) Encrypt(encryptStr string) (string, error) {
  39. // pem 解码
  40. block, _ := pem.Decode([]byte(pub.PublicKey))
  41. // x509 解码
  42. publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  43. if err != nil {
  44. return "", err
  45. }
  46. // 类型断言
  47. publicKey := publicKeyInterface.(*rsa.PublicKey)
  48. //对明文进行加密
  49. encryptedStr, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, []byte(encryptStr))
  50. if err != nil {
  51. return "", err
  52. }
  53. //返回密文
  54. return base64.URLEncoding.EncodeToString(encryptedStr), nil
  55. }
  56. func (pri *rsaPri) i() {}
  57. func (pri *rsaPri) Decrypt(decryptStr string) (string, error) {
  58. // pem 解码
  59. block, _ := pem.Decode([]byte(pri.PrivateKey))
  60. // X509 解码
  61. privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  62. if err != nil {
  63. return "", err
  64. }
  65. decryptBytes, err := base64.URLEncoding.DecodeString(decryptStr)
  66. //对密文进行解密
  67. decrypted, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, decryptBytes)
  68. //返回明文
  69. return string(decrypted), nil
  70. }