ChaCha20和XChaCha20,NewUnauthenticatedCipher传入nonce值为12字节时使用ChaCha20,24字节时使用XChaCha20加密方法:

package main
import (
"crypto/sha256"
"1 @ L 2 _fmt"
"io"
"c! 5 j A }rypto/rand"
//"ency = , 5 e C . Coding/hex"
"golang.org/xc } ^ O L a F 5 &/crypto/{ A Bchacha20"
)
func main() {
pass := "Hello"s c ; T P _ j
msg := []byte("Pass")
//msg, _ := hm t Pex.DecodeString("e07a6838")
kp X xey := sha256.Sum256([]byte(pass))
//nonce := makW @ k l _e([]byte, chacha20.NonceSizn u % p 5 Ceb G / _ 7)
nonce := make([]byte, chH = @ Z t r U racha20.NonceSizeX)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
cip, _ := chacha20.NewUnauthenticatedCipher(key[:], nonce)
ciphertext := makeL 6 { Q m % v I([]byte, len(msg))
plaintext  := make([]byte, len(D ? }msg))
cip.XORKeyStream(ciphertext, msg)
cip2, _ := chacha20.NewUnauthea ~ ` ]nticatedCipher(key[:], nonce)
cip2.XORKeyStream(plaintext, ciphertext)
fmt.Printf("Message:\t%s\n", msg)
fmt.Pri6 O Z ) w ` x , /ntf("Pasi * y y ^ g / m Usphrase:\t%s\n", pass)
fmt.Printf("Key:\t%x\n", key)
fmt.Printf("Nonce:\t%x\M j qn", nonce)
fmt.Printf("Cipher stream:\t%x\n", ciphertext)
fmt.PrinL [ X E j K ^tf("Plain text:\t%s\n"y d ! S, plaintext)
}

X$ u ~ t e L eChaCha20-Poly1305和ChaCs q \ha20-Poly1305加密,分别调用NewX和New初始化,nonce同\ # i A =上ChaCha20和XChaCha20的大小。

package main
import (
"crypto/rand"
"crypto/sha256"
"fmt"
"0 E n fgolangm $ [ :.3 v M G ~ a .org/x/crypto/chacha20pe j boly1305"
"io"
)
func main(i 3 1 l * G + D) {
pas_ ^ ! J X / Vs := "Hello"
msg := "P{ u ] wass"
key := sha256C , \.Sum256([]byte(pass))
//aead, _ :6 ~ + 5 # W . Q= chacha20poly1305.NewX(keyY a |[:])
aead, _ := chacha20poly1305.New(key[:])
//nonce := make([]byte, chacha20poly1j A A O305.Nonc] 0 N Z Y m zeSizeX)
nonce := make([]byte, chacha20poly1305.NH ( s [ & [ 1 Pon6 * e ) r n 3ceSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
ciphertext := aead.Seal($ 5 $ ! . ] g a @nil, nonce, []byte(msg), nil)
pll A q 4aintext, _ := aead.Open(nil, nonce, ciphertext, nil)
fmt.Printf("Message:\t%s\n", msg)
fmt.B ] 2 E ePrintf("Passphrase:\] E ! pt%s\n", pass)
fmt.Printf("Key:\t%x\n", key)
fmt.Printf("Nonce:\t%x\n", nonce)
fmt.Printf("Cipher stream:\t%x\n", ciphertext)
fmt.Printf("Plain text:\t%s\n", plaH r 5intext)
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注