我正在尝试使用端到端加密在 golang 中实现一个小型聊天服务器。服务器示例的启动 https://github.com/adonovan/gopl.io/tree/master/ch8/chat和客户https://github.com/adonovan/gopl.io/blob/master/ch8/netcat3/netcat.go我偶然发现 https://www.thepolyglotdeveloper.com/2018/02/encrypt-decrypt-data-golang-application-crypto-packages/在 Go 中加密和解密。
加密函数:
func encrypt(data []byte, passphrase string) []byte {
block, _ := aes.NewCipher([]byte(createHash(passphrase)))
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext
}
在 func main() 中:
ciphertext := encrypt([]byte(os.Stdin), "password")
mustCopy(conn, ciphertext)
conn.Close()
os.Stdin 是 os.file,而它需要作为 []byte。解决方案应该是 io.Reader 或通过缓冲区,但我找不到有效的解决方案。
我试过了
bytes.NewBuffer([]byte(os.Stdin))
和
reader := bytes.NewReader(os.Stdin)
我们非常欢迎任何意见。对不起,如果我在这里没有看到明显的问题/解决方案,因为我是新手。
最佳答案
os.Stdin
是一个 io.Reader
.您不能将它转换为 []byte
,但您可以从中读取,并且您从中读取的数据可能会读入 []byte
.
由于在许多终端中从 os.Stdin
中读取数据都是按行给出的,因此您应该从中读取完整的一行。从 os.Stdin
读取可能会阻塞,直到有完整的行可用。
为此你有很多可能性,一种是使用 bufio.Scanner
.
这是你可以做到的:
scanner := bufio.NewScanner(os.Stdin)
if !scanner.Scan() {
log.Printf("Failed to read: %v", scanner.Err())
return
}
line := scanner.Bytes() // line is of type []byte, exactly what you need
关于go - 将 os.Stdin 转换为 []byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50773514/