AES_ECB算法(golang)

package util

import (
	"bytes"
	"crypto/aes"
	"errors"
)

type AesECB struct {
	key       []byte
	blockSize int
}

func NewAesEcb(key []byte, blocksize int) *AesECB {
	return &AesECB{
		key: key,
		blockSize: blocksize,
	}
}

func (a *AesECB) Encrypt(src []byte, isPad ...bool) ([]byte, error) {
	block, err := aes.NewCipher(a.key)
	if err != nil {
		return nil, err
	}

	if len(src) == 0 {
		return nil, errors.New("content is empty")
	}

	if len(isPad) > 0 && isPad[0] == false {
		src = a.noPadding(src)
	} else {
		src = a.padding(src)
	}

	buf := make([]byte, a.blockSize)
	encrypted := make([]byte, 0)
	for i := 0; i < len(src); i += a.blockSize {
		block.Encrypt(buf, src[i:i+a.blockSize])
		encrypted = append(encrypted, buf...)
	}
	return encrypted, nil
}

func (a *AesECB) Decrypt(src []byte, isPad ...bool) ([]byte, error) {
	block, err := aes.NewCipher(a.key)
	if err != nil {
		return nil, err
	}
	if len(src) == 0 {
		return nil, errors.New("content is empty")
	}
	buf := make([]byte, a.blockSize)
	decrypted := make([]byte, 0)
	for i := 0; i < len(src); i += a.blockSize {
		block.Decrypt(buf, src[i:i+a.blockSize])
		decrypted = append(decrypted, buf...)
	}

	if len(isPad) > 0 && isPad[0] == false {
		decrypted = a.unNoPadding(decrypted)
	} else {
		decrypted = a.unPadding(decrypted)
	}

	return decrypted, nil
}

//nopadding模式
func (a *AesECB) noPadding(src []byte) []byte {
	count := a.blockSize - len(src)%a.blockSize
	if len(src)%a.blockSize == 0 {
		return src
	} else {
		return append(src, bytes.Repeat([]byte{byte(0)}, count)...)
	}
}

//nopadding模式
func (a *AesECB) unNoPadding(src []byte) []byte {
	for i := len(src) - 1; ; i-- {
		if src[i] != 0 {
			return src[:i+1]
		}
	}
	return nil
}

//padding模式
func (a *AesECB) padding(src []byte) []byte {
	count := a.blockSize - len(src)%a.blockSize
	padding := bytes.Repeat([]byte{byte(0)}, count)
	padding[count-1] = byte(count)
	return append(src, padding...)
}

//padding模式
func (a *AesECB) unPadding(src []byte) []byte {
	l := len(src)
	p := int(src[l-1])
	return src[:l-p]
}

使用:

//实例化
pwd := "asd123456"
aes := NewAesEcb([]byte(pwd), aes.BlockSize)

//定义加密的字符串
str := "hello world"

//加密
encrypted, err := aes.Encrypt(str, false)


//解密
decrypted, err := aes.Decrypt(encrypted, false)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值