本文采用的是AES的CBC模式, DES可以参考另外一篇文章
//初始化向量
var ivString = "a.osheng.win"
//AES加密
func AesEncrypt(src, key string) string {
plaintext := []byte(src)
keyByte := md5.Sum([]byte(key))
block, err := aes.NewCipher(keyByte[:])
if err != nil {
panic("invalid decrypt key")
}
blockSize := block.BlockSize()
plaintext = PKCS5Padding(plaintext, blockSize)
iv := []byte(ivDefValue)
blockMode := cipher.NewCBCEncrypter(block, iv)
ciphertext := make([]byte, len(plaintext))
blockMode.CryptBlocks(ciphertext, plaintext)
return fmt.Sprintf("%X", ciphertext)
}
//AES解密
func AesDecrypt(secret, key string) string{
ciphertext, _ := hex.DecodeString(secret)
keyByte := md5.Sum([]byte(key))
block, err := aes.NewCipher(keyByte[:])
if err != nil {
panic("invalid decrypt key")
}
blockSize := block.BlockSize()
if len(ciphertext) < blockSize {
panic("ciphertext too short")
}
iv := []byte(ivString)
if len(ciphertext)%blockSize != 0 {
panic("ciphertext is not a multiple of the block size")
}
blockModel := cipher.NewCBCDecrypter(block, iv)
plaintext := make([]byte, len(ciphertext))
blockModel.CryptBlocks(plaintext, ciphertext)
plaintext = PKCS5UnPadding(plaintext)
return string(plaintext)
}
//明文补码算法
func PKCS5Padding(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
//明文减码算法
func PKCS5UnPadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}