加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang加密系列之AES

发布时间:2020-12-16 18:39:40 所属栏目:大数据 来源:网络整理
导读:Golang加密系列之AES Golang加密系列之RSA 这里我们只讨论使用aes加密算法,pkcs7padding,CBC模式模式进行加密。 加密代码: funcEncrypt(plantText,key[]byte)([]byte,error){block,err:=aes.NewCipher(key)//选择加密算法iferr!=nil{returnnil,err}plantTe
  1. Golang加密系列之AES

  2. Golang加密系列之RSA

这里我们只讨论使用aes加密算法,pkcs7padding,CBC模式模式进行加密。

加密代码:

funcEncrypt(plantText,key[]byte)([]byte,error){
block,err:=aes.NewCipher(key)//选择加密算法
iferr!=nil{
returnnil,err
}
plantText=PKCS7Padding(plantText,block.BlockSize())

blockModel:=cipher.NewCBCEncrypter(block,key[:block.BlockSize()])

ciphertext:=make([]byte,len(plantText))

blockModel.CryptBlocks(ciphertext,plantText)
returnciphertext,nil
}

funcPKCS7Padding(ciphertext[]byte,blockSizeint)[]byte{
padding:=blockSize-len(ciphertext)%blockSize
padtext:=bytes.Repeat([]byte{byte(padding)},padding)
returnappend(ciphertext,padtext...)
}

解密代码:

funcDecrypt(ciphertext,err
}
blockModel:=cipher.NewCBCDecrypter(block,key[:block.BlockSize()])
plantText:=make([]byte,len(ciphertext))
blockModel.CryptBlocks(plantText,ciphertext)
plantText=PKCS7UnPadding(plantText,block.BlockSize())
returnplantText,nil
}

funcPKCS7UnPadding(plantText[]byte,blockSizeint)[]byte{
length:=len(plantText)
unpadding:=int(plantText[length-1])
returnplantText[:(length-unpadding)]
}

OK,代码上完,需要立刻能干活的童鞋,直接command+c & command+v 就OK了,想折腾的童鞋接着往下看,我们来讨论下相关的概念性的东西,

AES:高级加密标准(Advanced Encryption Standard),又称Rijndael加密法,这个标准用来替代原先的DES。AES加密数据块分组长度必须为128bit(byte[16]),密钥长度可以是128bit(byte[16])、192bit(byte[24])、256bit(byte[32])中的任意一个。

块:对明文进行加密的时候,先要将明文按照128bit进行划分。

填充方式:因为明文的长度不一定总是128的整数倍,所以要进行补位,我们这里采用的是PKCS7填充方式,关于PKCS7,请戳这里

模式:这个,介绍起来有点复杂,请戳


嗯,加密解密,做了个包放在github上了,欢迎提bug,

地址:https://github.com/89hmdys/toast

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读