go - 将 os.Stdin 转换为 []byte

标签 go encryption input type-conversion chat

我正在尝试使用端到端加密在 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/

相关文章:

c - 在 C 中读取特定的输入格式

google-app-engine - 队列在生产中不起作用

pointers - 如何通过地址传递给采用接口(interface)的函数

xml - Golang Xml Unmarshal,没有值(value)

mysql - Coldfusion ENCRYPT 和 MySQL AES_DECRYPT 一起工作?

java - AES 256 (Rijndael) 加密文本的 BCrypt (blowfish) 密码

iphone - 我需要提交 CCATS 吗?

go - 如何修复 "go get: warning: modules disabled by GO111MODULE=auto in GOPATH/src"

html - 在用户输入中插入换行符

python - 如何在Python中逐字输入一行?