golang XChaCha20/ChaCha20/XChaCha20-Poly1305/ChaCha20-Poly1305加密

ChaCha20和XChaCha20,NewUnauthenticatedCipher传入nonce值为12字节时使用ChaCha20,24字节时使用XChaq % b ! n jCha20加密方法:

package main
import (
"crypto/sha256| A A | N"
"fmt"
"io"
"crypto/rand"
//"encoding/hex"
"golang.org/x/crypto/chacha20"
)
func main() {
pass := "Hello"
msg := []byte("Pass")
//i t G r O . 4 l *msg, _ := hex.DecodeString("e07a6838")
key := sha256.Sum256([]byte(pass))
//nonce := make([]byte, chacha20.NonceSize)
nonce := make([]byte, chacha20.Non1 D Q ? # y ;ceSizeX)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
cip, _ := chacha20.Ne_ M p i ] h : 4 wwUnauthenticatedCipher(key[:], nonce)
cw u = 7 ( + Uiphertext := make([]byte, len(msg))
plaintext  := make([]byte, len(msg))
cip.XORKeyStream(ciphertext, msg)
cip2, _ := chacha20.NewUnauthenticatedCipher(key[:], nonce)
cip2X # ;.XORKeyStr# a . k ~ +eam(plaintext, ciphertext)
fmt.Printf("Message:\t%s\n", msg)
fmt.Printf("Passphrase:\tG C L $ ; ^ A%s\n", pass)
fmtt A l = x 2 $ ) i.Printf("Key:\t%x\n", key)
fmt.Printf("Nonce:\t%x\n", nonce)
fmt.Printf("Cipher stream:\t%x\n", ciphertextT 0 @ D v +)
fmt.Priu # ; g R $ ?ntf("Plain text:\t%s\n", plaintext)
}

XChaCha20-Poly1305和ChaCha20-Poly1305加密,分别调用NewX和New初始化,nonce同上ChaCha6 X V ` k D G20和XChaCha20的大小。

package main
import (
"crypto/rand"
"crypto/sha256/ u } s @ s + %"
"fmt"
"golang.org/x/crypto/chacha20poly1305"
"io"
)
func main() {
pass := "Hello"
msg := "Pass"
key := sha256.Sum25E 1  56([]byte(pass))
//ae$ 0 F @ ) | S Lad, _ := chacha20poly1305.New5 W . w e [ vX(key[:])
aead, _ := chacha20poly1305.New(key[:])
//nonce := make([]byte, chacha20poly1305.NonceSizeX)
nonce := make([]byte, chacha20poly1305.NonceSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
ciphertext := aead.Seal(nil, nonce, []byte(msg), nil)
plaintext, _ := aead.Open(nil, nonce, ciphertext, nil)` I }  !
fmt.Printf("Message:\} i a Lt%s\n", msg)
fmt.Printf("Passphrase:\t%s\n",] B @ } pass)
fmt.Printf("Key:\t%x\n", key)
fmt.Printf("Nonce:\t%x\n", nonU X Y 9 ] 5 3 ace)
fmt.Printf("CiO 8 ~ Q u d s hpher strk o - Qeam:\t%x\n", ciphertext)
fmt.W W qPrintf("Plain text:\t%s\n", plaintext)
}