Go语言加密算法之AES(CBC模式)

本文采用的是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)]
}

转载于:https://my.oschina.net/imhuayi/blog/1833340

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值