最後活躍 1710345461

AimerNeige's Avatar AimerNeige 已修改 1710345461. 還原成這個修訂版本

1 file changed, 43 insertions

aes.go(檔案已創建)

@@ -0,0 +1,43 @@
1 + package utils
2 +
3 + import (
4 + "bytes"
5 + "crypto/aes"
6 + "crypto/cipher"
7 + )
8 +
9 + func encrypt(aesKey, plaintextMsg []byte) ([]byte, error) {
10 + block, err := aes.NewCipher(aesKey)
11 + if err != nil {
12 + return []byte{}, err
13 + }
14 + plaintextMsg = pkcs5Padding(plaintextMsg, block.BlockSize())
15 + cipherText := make([]byte, len(plaintextMsg))
16 + cipher.NewCBCEncrypter(block, aesKey[:block.BlockSize()]).
17 + CryptBlocks(cipherText, plaintextMsg)
18 + return cipherText, nil
19 + }
20 +
21 + func decrypt(aesKey, encryptMsg []byte) ([]byte, error) {
22 + block, err := aes.NewCipher(aesKey)
23 + if err != nil {
24 + return []byte{}, err
25 + }
26 + decryptedMsg := make([]byte, len(encryptMsg))
27 + cipher.NewCBCDecrypter(block, aesKey[:block.BlockSize()]).
28 + CryptBlocks(decryptedMsg, encryptMsg)
29 + decryptedMsg = pkcs5UnPadding(decryptedMsg)
30 + return encryptMsg, nil
31 + }
32 +
33 + func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
34 + padding := blockSize - len(ciphertext)%blockSize
35 + padtext := bytes.Repeat([]byte{byte(padding)}, padding)
36 + return append(ciphertext, padtext...)
37 + }
38 +
39 + func pkcs5UnPadding(origData []byte) []byte {
40 + length := len(origData)
41 + unpadding := int(origData[length-1])
42 + return origData[:(length - unpadding)]
43 + }
上一頁 下一頁