将 os.Stdin 转换为 []byte
Convert os.Stdin to []byte
我正在尝试使用端到端加密在 golang 中实现一个小型聊天服务器。开始服务器 https://github.com/adonovan/gopl.io/tree/master/ch8/chat and client https://github.com/adonovan/gopl.io/blob/master/ch8/netcat3/netcat.go I stumbled upon 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)
欢迎任何意见。对不起,如果我在这里没有看到明显的 problem/solution,因为我是新手。
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
我正在尝试使用端到端加密在 golang 中实现一个小型聊天服务器。开始服务器 https://github.com/adonovan/gopl.io/tree/master/ch8/chat and client https://github.com/adonovan/gopl.io/blob/master/ch8/netcat3/netcat.go I stumbled upon 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)
欢迎任何意见。对不起,如果我在这里没有看到明显的 problem/solution,因为我是新手。
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