github.com/polarismesh/polaris@v1.17.8/plugin/crypto/aes/aes_test.go (about) 1 /** 2 * Tencent is pleased to support the open source community by making Polaris available. 3 * 4 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. 5 * 6 * Licensed under the BSD 3-Clause License (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * https://opensource.org/licenses/BSD-3-Clause 11 * 12 * Unless required by applicable law or agreed to in writing, software distributed 13 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 * specific language governing permissions and limitations under the License. 16 */ 17 18 package aes 19 20 import ( 21 "encoding/hex" 22 "testing" 23 24 "github.com/stretchr/testify/assert" 25 ) 26 27 func Test_AESCrypto_GenerateKey(t *testing.T) { 28 tests := []struct { 29 name string 30 keyLen int 31 err error 32 }{ 33 { 34 name: "genrate aes key", 35 keyLen: 16, 36 }, 37 } 38 for _, tt := range tests { 39 t.Run(tt.name, func(t *testing.T) { 40 c := &AESCrypto{} 41 got, err := c.GenerateKey() 42 assert.Nil(t, err) 43 assert.Equal(t, tt.keyLen, len(got)) 44 t.Logf("%x", got) 45 t.Log(hex.EncodeToString(got)) 46 }) 47 } 48 } 49 50 func Test_AESCrypto_Encrypt(t *testing.T) { 51 type args struct { 52 plaintext string 53 key []byte 54 } 55 key, _ := hex.DecodeString("777b162a185673cb1b72b467a78221cd") 56 tests := []struct { 57 name string 58 args args 59 want string 60 wangErr error 61 }{ 62 { 63 name: "encrypt to base64", 64 args: args{ 65 plaintext: "polaris", 66 key: key, 67 }, 68 want: "YnLZ0SYuujFBHjYHAZVN5A==", 69 }, 70 } 71 for _, tt := range tests { 72 t.Run(tt.name, func(t *testing.T) { 73 c := &AESCrypto{} 74 ciphertext, err := c.Encrypt(tt.args.plaintext, tt.args.key) 75 assert.Equal(t, tt.want, ciphertext) 76 assert.Equal(t, tt.wangErr, err) 77 }) 78 } 79 } 80 81 func Test_AESCrypto_Decrypt(t *testing.T) { 82 type args struct { 83 base64Ciphertext string 84 key []byte 85 } 86 key, _ := hex.DecodeString("777b162a185673cb1b72b467a78221cd") 87 tests := []struct { 88 name string 89 args args 90 want string 91 wantErr error 92 }{ 93 { 94 name: "decrypt from base64", 95 args: args{ 96 base64Ciphertext: "YnLZ0SYuujFBHjYHAZVN5A==", 97 key: key, 98 }, 99 want: "polaris", 100 }, 101 } 102 for _, tt := range tests { 103 t.Run(tt.name, func(t *testing.T) { 104 c := &AESCrypto{} 105 got, err := c.Decrypt(tt.args.base64Ciphertext, tt.args.key) 106 assert.Equal(t, tt.want, got) 107 assert.Equal(t, tt.wantErr, err) 108 }) 109 } 110 }