123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
-
-
- package encrypt
-
- import (
- "bytes"
- "crypto/aes"
- "crypto/cipher"
- "errors"
- )
-
-
-
- func MsgEncode(data, key []byte) ([]byte, error) {
- if nil == data || len(data) == 0 {
- return nil, errors.New("待加密 消息 为空")
- }
-
- if nil == key || len(key) == 0 {
- return nil, errors.New("加密 AESKey 为空")
- }
-
- block, e2 := aes.NewCipher(key)
- if e2 != nil {
- return nil, e2
- }
-
- blockSize := block.BlockSize()
- cipherData := pkcs7(data, blockSize)
- dist := make([]byte, len(cipherData))
-
-
- mode := cipher.NewCBCEncrypter(block, key[:blockSize])
- mode.CryptBlocks(dist, cipherData)
-
-
-
-
- return dist, nil
- }
-
-
-
- func MsgDecode(data, key []byte) ([]byte, error) {
- if nil == data || len(data) == 0 {
- return nil, errors.New("待解密 消息 为空")
- }
-
- if nil == key || len(key) == 0 {
- return nil, errors.New("解密 AESKey 为空")
- }
-
- block, err := aes.NewCipher(key)
- if err != nil {
- return nil, err
- }
-
- blockSize := block.BlockSize()
- dist := make([]byte, len(data))
-
- mode := cipher.NewCBCDecrypter(block, key[:blockSize])
- mode.CryptBlocks(dist, data)
-
-
-
- return unpkcs7(dist), nil
- }
-
-
- func pkcs7(data []byte, blockSize int) []byte {
- paddingBlock := blockSize - len(data)%blockSize
- if paddingBlock == 0 {
- paddingBlock = blockSize
- }
-
- padding := bytes.Repeat([]byte{byte(paddingBlock)}, paddingBlock)
- return append(data, padding...)
- }
-
-
- func unpkcs7(data []byte) []byte {
- length := len(data)
-
- unpadding := int(data[length-1])
- return data[:(length - unpadding)]
- }
|