前端之家收集整理的这篇文章主要介绍了
Golang1.7.3使用标准库的AES加密解密不实用扩展协议,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
type tobytes struct {
cip cipher.Block
pdgtext []byte
}
func main() {
cip,_ := aes.NewCipher([]byte("1234567891234567"))
enc := &tobytes{cip: cip,pdgtext: make([]byte,cip.BlockSize())}
src := enc.Encrypt([]byte("czxichen"))
dst := enc.Decrypt(src)
fmt.Println(string(dst))
}
func (a *tobytes) Encrypt(src []byte) (dst []byte) {
src = a.padding(src)
dst = make([]byte,len(src))
var index int = 0
for len(src) > 0 {
a.cip.Encrypt(dst[index:index+a.cip.BlockSize()],src)
index += a.cip.BlockSize()
src = src[a.cip.BlockSize():]
}
return dst
}
func (a *tobytes) Decrypt(src []byte) (dst []byte) {
if len(src)%a.cip.BlockSize() != 0 {
return src
}
dst = make([]byte,len(src))
var index int = 0
for len(src) > 0 {
a.cip.Decrypt(dst[index:index+a.cip.BlockSize()],src)
index += a.cip.BlockSize()
src = src[a.cip.BlockSize():]
}
return a.unpadding(dst)
}
func (a *tobytes) padding(src []byte) (dst []byte) {
pdg := a.cip.BlockSize() - len(src)%a.cip.BlockSize()
p := a.pdgtext[:pdg]
p[pdg-1] = byte(pdg)
return append(src,p...)
}
func (a *tobytes) unpadding(src []byte) (dst []byte) {
length := len(src)
if length <= 0 {
return src
}
return src[:(length - int(src[length-1]))]
}
原文链接:https://www.f2er.com/go/189181.html