golang实现chacha20和chacha20poly1305加密解密
本来之前是想打算用aes来加密数据库数据的,但是后面看到了chacha20,了解了一下就选择了后者,但是中文互联网上没找到golang的实现,故贴出来一下帮助以后搜索的萌新……
chacha20包信息 https://pkg.go.dev/golang.org/x/crypto/chacha20
chacha20poly1305包信息 https://pkg.go.dev/golang.org/x/crypto/chacha20poly1305
文档上面说要安全性的话更推荐chacha20poly1305,但是chacha20poly1305加密后的数据比chacha20大了很多,这就看自己的选择了
直接上代码
func chacha20_func() { msg := []byte("你是我的小啊小苹果") key := make([]byte, chacha20.KeySize) nonce := make([]byte, chacha20.NonceSize) encryption, _ := chacha20.NewUnauthenticatedCipher(key, nonce) ciphertext := make([]byte, len(msg)) encryption.XORKeyStream(ciphertext, msg) fmt.Println("chacha20加密:", hex.EncodeToString(ciphertext)) decrypt, _ := chacha20.NewUnauthenticatedCipher(key, nonce) plaintext := make([]byte, len(msg)) decrypt.XORKeyStream(plaintext, ciphertext) fmt.Println("chacha20解密:", string(plaintext)) } func chacha20_1305_func() { msg := []byte("你是我的小啊小苹果") key := make([]byte, chacha20poly1305.KeySize) nonce := make([]byte, chacha20poly1305.NonceSize) aead, err := chacha20poly1305.New(key) if err != nil { panic(err) } ciphertext := aead.Seal(nil, nonce, msg, nil) fmt.Println("chacha20poly1305加密:", hex.EncodeToString(ciphertext)) plaintext, _ := aead.Open(nil, nonce, ciphertext, nil) fmt.Println("chacha20poly1305解密:", string(plaintext)) }