12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
-
-
- 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
- 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)]
- }
|