當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO StreamWriter用法及代碼示例

GO語言"crypto/cipher"包中"StreamWriter"類型的用法及代碼示例。

StreamWriter 將 Stream 包裝到 io.Writer 中。它調用 XORKeyStream 來處理通過的每個數據片。如果任何 Write 調用返回短,則 StreamWriter 不同步,必須丟棄。 StreamWriter 沒有內部緩衝;不需要調用 Close 來刷新寫入數據。

用法:

type StreamWriter struct {
    S   Stream
    W   io.Writer
    Err error // unused
}

例子:

package main

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "encoding/hex"
    "fmt"
    "io"
)

func main() {
    // Load your secret key from a safe place and reuse it across multiple
    // NewCipher calls. (Obviously don't use this example key for anything
    // real.) If you want to convert a passphrase to a key, use a suitable
    // package like bcrypt or scrypt.
    key, _ := hex.DecodeString("6368616e676520746869732070617373")

    bReader := bytes.NewReader([]byte("some secret text"))

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    // If the key is unique for each ciphertext, then it's ok to use a zero
    // IV.
    var iv [aes.BlockSize]byte
    stream := cipher.NewOFB(block, iv[:])

    var out bytes.Buffer

    writer := &cipher.StreamWriter{S: stream, W: &out}
    // Copy the input to the output buffer, encrypting as we go.
    if _, err := io.Copy(writer, bReader); err != nil {
        panic(err)
    }

    // Note that this example is simplistic in that it omits any
    // authentication of the encrypted data. If you were actually to use
    // StreamReader in this manner, an attacker could flip arbitrary bits in
    // the decrypted result.

    fmt.Printf("%x\n", out.Bytes())
}

輸出:

cf0495cc6f75dafc23948538e79904a9

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 StreamWriter。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。