dongshang1979 2018-06-09 10:57
浏览 92
已采纳

将os.Stdin转换为[] byte

I'm trying to implement a small chat-server in golang with end-to-end encryption. Starting of the example for server 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/ to encrypt and decrypt in Go.

The function to encrypt:

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
}

in func main():

   ciphertext := encrypt([]byte(os.Stdin), "password")
    mustCopy(conn, ciphertext)
    conn.Close()

os.Stdin is os.file, while it is needed as []byte. The solution should be io.Reader or via buffer, but I can't find a working solution.

I tried

bytes.NewBuffer([]byte(os.Stdin))

and

reader := bytes.NewReader(os.Stdin)

Any input is more than welcome. Sorry if I'm not seeing the obvious problem/solution here, as I'm fairly new.

  • 写回答

1条回答 默认 最新

  • douyan3478 2018-06-09 11:07
    关注

    os.Stdin is an io.Reader. You can't convert it to a []byte, but you can read from it, and the data you read from it, that may be read into a []byte.

    Since in many terminals reading from os.Stdin gives data by lines, you should read a complete line from it. Reading from os.Stdin might block until a complete line is available.

    For that you have many possibilities, one is to use bufio.Scanner.

    This is how you can do it:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?