大佬教程收集整理的这篇文章主要介绍了加密 – Golang,使用AES和Base64加密字符串,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试了几种方法,包括第三方库@L_874_3@无效。使用以下方法加密/解密8/10个项目,但似乎在加密/解密中的某个时间点留下了一些填充残差。因为它是我的代码是这样的:
package client import ( "encoding/base64" "crypto/aes" "crypto/cipher" "fmt" ) var iv = []byte{34,35,57,68,4,36,7,8,23,86,23} func encodeBase64(b []bytE) String { return base64.StdEncoding.EncodeToString(b) } func decodeBase64(s String) []byte { data,err := base64.StdEncoding.DecodeString(s) if err != nil { panic(err) } return data } func Encrypt(key,text String) String { block,err := aes.NewCipher([]byte(key)) if err != nil { panic(err) } plaintext := []byte(text) cfb := cipher.NewCFBEncrypter(block,iv) ciphertext := make([]byte,len(plaintext)) cfb.XORKeyStream(ciphertext,plaintext) return encodeBase64(ciphertext) } func Decrypt(key,err := aes.NewCipher([]byte(key)) if err != nil { panic(err) } ciphertext := decodeBase64(text) cfb := cipher.NewCFBEncrypter(block,iv) plaintext := make([]byte,len(ciphertext)) cfb.XORKeyStream(plaintext,ciphertext) }
编辑:基于Kluyg关于IV创建的评论,我修改了示例代码,使用与linked示例相同的密文创建IV的推荐方法,从密文创建IV。 (在生产代码中,每次应该单独生成IV,感谢RoundSparrow hilltx指出这一点。)
我认为你遇到的问题是由于密钥长度无效,但我不是100%肯定的。
package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "errors" "fmt" "io" "log" ) func main() { key := []byte("a very very very very secret key") // 32 bytes plaintext := []byte("some really really really long plaintext") fmt.Printf("%s\n",plaintext) ciphertext,err := encrypt(key,plaintext) if err != nil { log.Fatal(err) } fmt.Printf("%0x\n",ciphertext) result,err := decrypt(key,ciphertext) if err != nil { log.Fatal(err) } fmt.Printf("%s\n",result) } // See alternate IV creation from ciphertext below //var iv = []byte{35,46,24,85,74,87,88,98,66,32,14,05} func encrypt(key,text []bytE) ([]byte,error) { block,err := aes.NewCipher(key) if err != nil { return nil,err } b := base64.StdEncoding.EncodeToString(text) ciphertext := make([]byte,aes.blockSize+len(b)) iv := ciphertext[:aes.blockSize] if _,err := io.ReadFull(rand.Reader,iv); err != nil { return nil,err } cfb := cipher.NewCFBEncrypter(block,iv) cfb.XORKeyStream(ciphertext[aes.blockSize:],[]byte(b)) return ciphertext,nil } func decrypt(key,err } if len(text) < aes.blockSize { return nil,errors.New("ciphertext too short") } iv := text[:aes.blockSize] text = text[aes.blockSize:] cfb := cipher.NewCFBDecrypter(block,iv) cfb.XORKeyStream(text,text) data,err := base64.StdEncoding.DecodeString(String(text)) if err != nil { return nil,err } return data,nil }
产品:
希望有助于指出问题。
以上是大佬教程为你收集整理的加密 – Golang,使用AES和Base64加密字符串全部内容,希望文章能够帮你解决加密 – Golang,使用AES和Base64加密字符串所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。