go: 封装chacha20 reader 因为rc4在流加密中已经不再安全,chacha20异军突起,现在用go封装一个reader,它从其它的io.Reader中读取数据,并转换为一个chacha20加密的数据: 代码: ```go package chacha20 import ( "crypto/sha256" "io" "golang.org/x/crypto/chacha20" ) type ChaCha20Reader struct { baseReader io.Reader passByte [32]byte cipher *chacha20.Cipher } func NewChaCha20Reader(pass string, nonce [24]byte, reader io.Reader) *ChaCha20Reader { c := new(ChaCha20Reader) c.baseReader = reader c.passByte = sha256.Sum256([]byte(pass)) c.cipher, _ = chacha20.NewUnauthenticatedCipher(c.passByte[:32], []byte(nonce[:])) return c } func (c *ChaCha20Reader) Read(p []byte) (n int, err error) { n, err = c.baseReader.Read(p) if err != nil { return n, err } p = p[:n] c.cipher.XORKeyStream(p, p) return n, nil } ``` 使用: ```go package chacha20 import ( "bytes" "crypto/rand" "fmt" "strings" "testing" ) func TestChacha20(t *testing.T) { pass := "hello" msg := "hello hello hello hello hello hello hello hello hello " // 加密 // 向量随机产生,解密时也需要同样的向量 nonceArray := [24]byte{} rand.Read(nonceArray[:]) r := NewChaCha20Reader(pass, nonceArray, strings.NewReader(msg)) bts, _ := ioutil.ReadAll(r) fmt.Println("encrypt:", bts) // 解密 r2 := NewChaCha20Reader(pass, nonceArray, bytes.NewReader(bts)) decBts, _ := ioutil.ReadAll(r2) fmt.Printf("decrypt:%s\n", decBts) } ``` 来自 大脸猪 写于 2020-05-29 18:01 -- 更新于2023-02-02 20:12 -- 0 条评论