1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
// 填充
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padText...)
}
// 加密
func Ase256(plaintext string, key string, iv string, blockSize int) string {
bKey := []byte(key)
bIV := []byte(iv)
bPlaintext := PKCS5Padding([]byte(plaintext), blockSize)
block, _ := aes.NewCipher(bKey)
ciphertext := make([]byte, len(bPlaintext))
mode := cipher.NewCBCEncrypter(block, bIV)
mode.CryptBlocks(ciphertext, bPlaintext)
return base64.StdEncoding.EncodeToString(ciphertext)
}
// 解密
func Aes256Decrypt(cryptData, key, iv string) ([]byte, error) {
ciphertext, err := base64.StdEncoding.DecodeString(cryptData)
if err != nil {
return nil, err
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, err
}
if len(ciphertext)%aes.BlockSize != 0 {
err = errors.New("ciphertext is not a multiple of the block size")
return nil, err
}
mode := cipher.NewCBCDecrypter(block, []byte(iv))
mode.CryptBlocks(ciphertext, ciphertext)
return ciphertext, err
}
|