代码地址:https://github.com/FakerGit/go-tools
加密模式
- AES ECB模式 PKCS7Padding填充
原理
整个明文分成若干段相同的小段,然后对每一小段进行加密。这个是不安全的,重复的原文块加密后会是重复的结果,很明显暴露明文的模式。
代码
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
func EcbDecrypt(data, key []byte) []byte {
block, _ := aes.NewCipher(key)
decrypted := make([]byte, len(data))
size := block.BlockSize()
for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
block.Decrypt(decrypted[bs:be], data[bs:be])
}
return PKCS7UnPadding(decrypted)
}
func EcbEncrypt(data, key []byte) []byte {
block, _ := aes.NewCipher(key)
data = PKCS7Padding(data, block.BlockSize())
decrypted := make([]byte, len(data))
size := block.BlockSize()
for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
block.Encrypt(decrypted[bs:be], data[bs:be])
}
return decrypted
}