github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zstring/aes_test.go (about) 1 package zstring_test 2 3 import ( 4 "testing" 5 6 zls "github.com/sohaha/zlsgo" 7 "github.com/sohaha/zlsgo/zstring" 8 ) 9 10 var ( 11 codeKey = "zHrM9pyM_RrvFf_fpssoJDEO5TatkhDh" 12 text = "待加密数据" 13 ) 14 15 func TestAes(t *testing.T) { 16 tt := zls.NewTest(t) 17 18 key := codeKey 19 str := zstring.String2Bytes(text) 20 21 cypted, err := zstring.AesEncrypt(str, key) 22 tt.EqualNil(err) 23 24 origdata, err := zstring.AesDecrypt(cypted, key) 25 tt.EqualNil(err) 26 27 tt.Equal(str, origdata) 28 tt.Equal(string(str), string(origdata)) 29 30 key = "" 31 _, err = zstring.AesEncrypt(str, key) 32 tt.EqualNil(err) 33 34 key = zstring.Pad("k", 16, "1", zstring.PadLeft) 35 _, err = zstring.AesEncrypt(str, key) 36 tt.EqualNil(err) 37 38 key = zstring.Pad("k", 17, "1", zstring.PadLeft) 39 _, err = zstring.AesEncrypt(str, key) 40 tt.EqualNil(err) 41 42 key = zstring.Pad("k", 25, "1", zstring.PadLeft) 43 _, err = zstring.AesEncrypt(str, key) 44 tt.EqualNil(err) 45 46 key = zstring.Pad("k", 38, "1", zstring.PadLeft) 47 _, err = zstring.AesEncrypt(str, key) 48 tt.EqualNil(err) 49 50 key = "是我呀" 51 _, err = zstring.AesEncrypt(str, key) 52 tt.EqualNil(err) 53 54 key = "是我呀,我是测试的人呢,你想干嘛呀???我就是试试看这么长会发生什么情况呢" 55 cypted, err = zstring.AesEncrypt(str, key) 56 tt.EqualNil(err) 57 str, err = zstring.AesDecrypt(cypted, key) 58 if err != nil { 59 t.Log(err) 60 } 61 t.Log(string(origdata), string(str)) 62 63 _, err = zstring.AesDecrypt([]byte("123"), "") 64 tt.Log(err) 65 tt.EqualTrue(err != nil) 66 } 67 68 func TestAesString(t *testing.T) { 69 tt := zls.NewTest(t) 70 71 key := codeKey 72 s := text 73 crypt, err := zstring.AesEncryptString(s, key) 74 tt.EqualNil(err) 75 t.Log(crypt) 76 77 orig, err := zstring.AesDecryptString(crypt, key) 78 tt.EqualNil(err) 79 t.Log(orig) 80 81 tt.EqualExit(s, orig) 82 83 s = `{"ip":"11.11.11.11"}` 84 crypt, err = zstring.AesEncryptString(s, "a234567890123456", "kkmbfgyuiedslpau") 85 tt.EqualNil(err) 86 t.Log(crypt) 87 88 orig, err = zstring.AesDecryptString(crypt, "a234567890123456", "kkmbfgyuiedslpau") 89 tt.EqualNil(err) 90 t.Log(orig) 91 92 tt.EqualExit(s, orig) 93 94 key = "" 95 s = "" 96 crypt, err = zstring.AesEncryptString(s, key) 97 tt.EqualNil(err) 98 t.Log(crypt) 99 100 orig, err = zstring.AesDecryptString(crypt, key) 101 tt.EqualNil(err) 102 t.Log(orig) 103 104 tt.EqualExit(s, orig) 105 106 t.Log(crypt) 107 108 orig, err = zstring.AesDecryptString("crypt", key) 109 tt.Log(orig, err) 110 tt.EqualTrue(err != nil) 111 112 } 113 114 func TestAesGCM(t *testing.T) { 115 tt := zls.NewTest(t) 116 key := codeKey 117 118 crypt, err := zstring.AesGCMEncryptString(text, key) 119 tt.NoError(err) 120 121 plain, err := zstring.AesGCMDecryptString(crypt, key) 122 tt.NoError(err) 123 tt.Equal(text, plain) 124 125 plain, err = zstring.AesGCMDecryptString("oXvYLL+PNB6/rLAuQKpBIyysS1PnGNpm4F8ahVt7aYWp4AlIzCC512WShQ==", key) 126 tt.Equal(text, plain) 127 }