rsa_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package codec
  2. import (
  3. "encoding/base64"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/tal-tech/go-zero/core/fs"
  7. )
  8. const (
  9. priKey = `-----BEGIN RSA PRIVATE KEY-----
  10. MIICXQIBAAKBgQC4TJk3onpqb2RYE3wwt23J9SHLFstHGSkUYFLe+nl1dEKHbD+/
  11. Zt95L757J3xGTrwoTc7KCTxbrgn+stn0w52BNjj/kIE2ko4lbh/v8Fl14AyVR9ms
  12. fKtKOnhe5FCT72mdtApr+qvzcC3q9hfXwkyQU32pv7q5UimZ205iKSBmgQIDAQAB
  13. AoGAM5mWqGIAXj5z3MkP01/4CDxuyrrGDVD5FHBno3CDgyQa4Gmpa4B0/ywj671B
  14. aTnwKmSmiiCN2qleuQYASixes2zY5fgTzt+7KNkl9JHsy7i606eH2eCKzsUa/s6u
  15. WD8V3w/hGCQ9zYI18ihwyXlGHIgcRz/eeRh+nWcWVJzGOPUCQQD5nr6It/1yHb1p
  16. C6l4fC4xXF19l4KxJjGu1xv/sOpSx0pOqBDEX3Mh//FU954392rUWDXV1/I65BPt
  17. TLphdsu3AkEAvQJ2Qay/lffFj9FaUrvXuftJZ/Ypn0FpaSiUh3Ak3obBT6UvSZS0
  18. bcYdCJCNHDtBOsWHnIN1x+BcWAPrdU7PhwJBAIQ0dUlH2S3VXnoCOTGc44I1Hzbj
  19. Rc65IdsuBqA3fQN2lX5vOOIog3vgaFrOArg1jBkG1wx5IMvb/EnUN2pjVqUCQCza
  20. KLXtCInOAlPemlCHwumfeAvznmzsWNdbieOZ+SXVVIpR6KbNYwOpv7oIk3Pfm9sW
  21. hNffWlPUKhW42Gc+DIECQQDmk20YgBXwXWRM5DRPbhisIV088N5Z58K9DtFWkZsd
  22. OBDT3dFcgZONtlmR1MqZO0pTh30lA4qovYj3Bx7A8i36
  23. -----END RSA PRIVATE KEY-----`
  24. pubKey = `-----BEGIN PUBLIC KEY-----
  25. MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4TJk3onpqb2RYE3wwt23J9SHL
  26. FstHGSkUYFLe+nl1dEKHbD+/Zt95L757J3xGTrwoTc7KCTxbrgn+stn0w52BNjj/
  27. kIE2ko4lbh/v8Fl14AyVR9msfKtKOnhe5FCT72mdtApr+qvzcC3q9hfXwkyQU32p
  28. v7q5UimZ205iKSBmgQIDAQAB
  29. -----END PUBLIC KEY-----`
  30. testBody = `this is the content`
  31. )
  32. func TestCryption(t *testing.T) {
  33. enc, err := NewRsaEncrypter([]byte(pubKey))
  34. assert.Nil(t, err)
  35. ret, err := enc.Encrypt([]byte(testBody))
  36. assert.Nil(t, err)
  37. file, err := fs.TempFilenameWithText(priKey)
  38. assert.Nil(t, err)
  39. dec, err := NewRsaDecrypter(file)
  40. assert.Nil(t, err)
  41. actual, err := dec.Decrypt(ret)
  42. assert.Nil(t, err)
  43. assert.Equal(t, testBody, string(actual))
  44. actual, err = dec.DecryptBase64(base64.StdEncoding.EncodeToString(ret))
  45. assert.Nil(t, err)
  46. assert.Equal(t, testBody, string(actual))
  47. }
  48. func TestBadPubKey(t *testing.T) {
  49. _, err := NewRsaEncrypter([]byte("foo"))
  50. assert.Equal(t, ErrPublicKey, err)
  51. }