作者:时尚经典语录覀--- | 来源:互联网 | 2023-09-24 02:12
Go语言实现AES加密算法(CBC模式)
AES是目前比较流行的对称加密算法,是一种分组密码算法,AES的分组长度为128比特(16字节),而密钥长度可以是128比特、192比特或256比特。CBC模式(密码分组链接模式)是常用的一种分组密码的模式。(点击查看分组密码及CBC模式概述)
实现代码如下:
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"bytes"
)
func Padding(plainText []byte,blockSize int) []byte{
n:= blockSize-len(plainText)%blockSize
temp:=bytes.Repeat([]byte{byte(n)},n)
plainText=append(plainText,temp...)
return plainText
}
func UnPadding(cipherText []byte) []byte{
end:=cipherText[len(cipherText)-1]
cipherText=cipherText[:len(cipherText)-int(end)]
return cipherText
}
func AES_CBC_Encrypt(plainText []byte,key []byte) []byte{
block,err:=aes.NewCipher(key)
if err!=nil{
panic(err)
}
plainText=Padding(plainText,block.BlockSize())
iv:=[]byte("12345678abcdefgh")
blockMode:=cipher.NewCBCEncrypter(block,iv)
cipherText:=make([]byte,len(plainText))
blockMode.CryptBlocks(cipherText,plainText)
return cipherText
}
func AES_CBC_Decrypt(cipherText []byte,key []byte) []byte{
block,err:=aes.NewCipher(key)
if err!=nil{
panic(err)
}
iv:=[]byte("12345678abcdefgh")
blockMode:=cipher.NewCBCDecrypter(block,iv)
plainText:=make([]byte,len(cipherText))
blockMode.CryptBlocks(plainText,cipherText)
plainText=UnPadding(plainText)
return plainText
}
测试代码如下:
func main(){
message:=[]byte("Hello!My name is X.")
key:=[]byte("abcdefgh98765432")
cipherText:=AES_CBC_Encrypt(message,key)
fmt.Println("加密后为:",string(cipherText))
plainText:=AES_CBC_Decrypt(cipherText,key)
fmt.Println("解密后为:",string(plainText))
}
测试结果如下: