账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    求一个 go 中的 aes 加密方法
    60
    0
    要求如下:str = `406BF0AD11310101220213481000320000`key := `ER2Fb6ts3ECX`通过 AES 加密(加解密算法 AES/工作模式 ECB /填充方式 NoPadding)并根据 base64转码后字符串位:rebZn7aj61hD3lfsUrhwFgVzPg4yYo9aseP/a4sNTRIh/Vtb0mziFfoHdOZBZ5ujgoogle一番,找到一些代码,试了试都不太对package xaesimport ( "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 mainimport ( "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)}
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部