要求如下:
str = `406BF0AD11310101220213481000320000`
key := `ER2Fb6ts3ECX`
通过 AES 加密(加解密算法 AES/工作模式 ECB /填充方式 NoPadding)并根据 base64
转码后字符串位:
rebZn7aj61hD3lfsUrhwFgVzPg4yYo9aseP/a4sNTRIh/Vtb0mziFfoHdOZBZ5uj
试过了论坛中一位大老的方法,出来的结果貌似不一样呀~
package xaes
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
)
type Aes struct {
key []byte
}
func NewAes(key string) (*Aes) {
if key == "" {
panic("aes key empty")
}
sum := sha256.Sum256([]byte(key))
return &Aes{
key:sum[:],
}
}
func (a *Aes) Encrypt(encodeBytes []byte) (val string, err error) {
block, err := aes.NewCipher(a.key)
if err != nil {
return
}
blockSize := block.BlockSize()
encodeBytes = zeroPadding(encodeBytes, blockSize)
iv := make([]byte, blockSize)
_,err = rand.Read(iv)
if err != nil {
return
}
blockMode := cipher.NewCBCEncrypter(block, iv)
crypted := make([]byte, len(encodeBytes))
blockMode.CryptBlocks(crypted, encodeBytes)
iv = append(iv,crypted...)
val = base64.StdEncoding.EncodeToString(iv)
return
}
func (a *Aes) pkCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func (a *Aes) Decrypt(decodeBytes []byte) (origData []byte,err error) {
//decodeBytes, err := base64.StdEncoding.DecodeString(decodeStr)
//if err != nil {
// return
//}
block, err := aes.NewCipher(a.key)
if err != nil {
return nil, err
}
if len(decodeBytes) < block.BlockSize() {
err = errors.New("decodeBytes 长度不足")
return
}
iv := decodeBytes[:block.BlockSize()]
decodeBytes = decodeBytes[block.BlockSize():]
blockMode := cipher.NewCBCDecrypter(block, iv)
origData = make([]byte, len(decodeBytes))
blockMode.CryptBlocks(origData, decodeBytes)
origData = zeroUnPadding(origData)
return
}
func (a *Aes) pkCS5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
func zeroPadding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padText := bytes.Repeat([]byte{0}, padding)
return append(ciphertext, padText...)
}
func zeroUnPadding(origData []byte) []byte {
return bytes.TrimFunc(origData,
func(r rune) bool {
return r == rune(0)
})
}
调用方式
package main
import (
"awesomeProject/xaes"
"fmt"
)
func main() {
str := []byte("406BF0AD11310101220213481000320000")
xa := xaes.NewAes("ER2Fb6ts3ECX")
b,e:=xa.Encrypt(str)
if e != nil{
fmt.Println(e.Error())
return
}
fmt.Println(b)
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.