模块介绍

使用 rsa 非对称加密算法,进行加密解密,已实现公钥加密、私钥解密。

方法说明

方法 说明
ras.NewPublic(publicKey).Encrypt(encryptStr string) 公钥加密
rsa.NewPrivate(privateKey).Decrypt(decryptStr string) 私钥解密

测试用例

  1. func TestEncrypt(t *testing.T) {
  2. str, err := NewPublic(publicKey).Encrypt("123456")
  3. if err != nil {
  4. t.Error("rsa public encrypt error", err)
  5. return
  6. }
  7. t.Log(str)
  8. }
  9. func TestDecrypt(t *testing.T) {
  10. decryptStr := "KTKXckjkCLI6Vk_y_XROnY-a6nJpllruL-CX-v_2AFxfghA2tZ2nkQyS6d1-IIYMlgwm4ivwlzy-phLtaN9BB03htA5D9rwjA_JwYtqAG4iwuvgaDl2SiZ_H2ACv-aV1kNRgnyjh14hs0JiSt5VHEiJ3D2xYzOCKwtEzoo0WczJ-MYb3u_-bfcnm9YtvgtG5-y3Jy7WYr-IwXdBKqPO0E-jzrtY7m3Q1yC4znHdzjNpxCj0I6YRx4CZ362b706qNX7sl3E5KTJeSmYrsurB-SxQT1CaqGzVt7mshx1v2qGnv5NBNXpj7ZPKWGJbgaCUxcuxd1Mg0o81HnfbsGuSlFQ=="
  11. str, err := NewPrivate(privateKey).Decrypt(decryptStr)
  12. if err != nil {
  13. t.Error("rsa private decrypt error", err)
  14. return
  15. }
  16. t.Log(str)
  17. }

基准测试

  1. func BenchmarkEncryptAndDecrypt(b *testing.B) {
  2. b.ResetTimer()
  3. rsaPublic := NewPublic(publicKey)
  4. rsaPrivate := NewPrivate(privateKey)
  5. for i := 0; i < b.N; i++ {
  6. encryptString, _ := rsaPublic.Encrypt("123456")
  7. rsaPrivate.Decrypt(encryptString)
  8. }
  9. }
  10. // 输出
  11. goos: darwin
  12. goarch: amd64
  13. pkg: github.com/xinliangnote/go-gin-api/pkg/rsa
  14. BenchmarkEncryptAndDecrypt
  15. BenchmarkEncryptAndDecrypt-12 879 1326145 ns/op
  16. PASS
  17. Process finished with exit code 0