123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
-
-
- package encrypt
-
- import (
- "bytes"
- "crypto/aes"
- "crypto/cipher"
- "encoding/base64"
- "errors"
- )
-
-
-
- func MsgEncode(data []byte, encodingAESKey, iv string) ([]byte, error) {
- if encodingAESKey == "" {
- return nil, errors.New("加密 EncodingAESKey 为空")
- }
-
- if iv == "" {
- return nil, errors.New("加密 IV 为空")
- }
-
- if nil == data || len(data) == 0 {
- return nil, errors.New("待加密 消息 为空")
- }
-
- aesKey, e1 := base64.StdEncoding.DecodeString(encodingAESKey + "=")
- if e1 != nil {
- return nil, e1
- }
-
- block, e2 := aes.NewCipher(aesKey)
- if e2 != nil {
- return nil, e2
- }
-
- blockSize := block.BlockSize()
- dist := pkcs7(data, blockSize)
-
-
- mode := cipher.NewCBCEncrypter(block, []byte(iv))
- mode.CryptBlocks(dist, data)
-
-
-
-
- return dist, nil
- }
-
-
-
- func MsgDecode(data []byte, encodingAESKey, iv string) ([]byte, error) {
- if encodingAESKey == "" {
- return nil, errors.New("解密 EncodingAESKey 为空")
- }
-
- if iv == "" {
- return nil, errors.New("解密 IV 为空")
- }
-
- if nil == data || len(data) == 0 {
- return nil, errors.New("待解密 消息 为空")
- }
-
- aesKey, e1 := base64.StdEncoding.DecodeString(encodingAESKey + "=")
- if e1 != nil {
- return nil, e1
- }
-
- block, err := aes.NewCipher(aesKey)
- if err != nil {
- return nil, err
- }
-
- dist := make([]byte, len(data))
-
- mode := cipher.NewCBCDecrypter(block, []byte(iv))
- 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)]
- }
|