package server
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
//AES ECB模式加密
func AesECBEncrypt(plainText, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ecb := NewECBEncrypter(block)
plainText = PKCS5Padding(plainText, block.BlockSize())
crypted := make([]byte, len(plainText))
ecb.CryptBlocks(crypted, plainText)
return crypted, err
}
//AES ECB模式解密
func AESECBDecrypt(cipherText, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := NewECBDecrypter(block)
plainText := make([]byte, len(cipherText))
blockMode.CryptBlocks(plainText, cipherText)
plainText = PKCS5UnPadding(plainText)
return plainText, err
}
//AES CBC模式加密
func AESCBCEncrypt(plainText, key []byte) {
}
func PKCS5Padding(plainText []byte, blockSize int) []byte {
padding := blockSize - (len(plainText) % blockSize)
padText := bytes.Repeat([]byte{byte(padding)}, padding)
newText := append(plainText, padText...)
return newText
}
func PKCS5UnPadding(plainText []byte) []byte {
length := len(plainText)
number := int(plainText[length-1])
return plainText[:length-number]
}
type ecb struct {
b cipher.Block
blockSize int
}
func newECB(b cipher.Block) *ecb {
return &ecb{
b: b,
blockSize: b.BlockSize(),
}
}
type ecbEncrypter ecb
func NewECBEncrypter(block cipher.Block) cipher.BlockMode {
return (*ecbEncrypter)(newECB(block))
}
func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Encrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}
type ecbDecrypter ecb
// NewECBDecrypter returns a BlockMode which decrypts in electronic code book
// mode, using the given Block.
func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
return (*ecbDecrypter)(newECB(b))
}
func (x *ecbDecrypter) BlockSize() int { return x.blockSize }
func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Decrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}