Created
November 19, 2014 12:31
-
-
Save ggicci/a7593e989387a8087b04 to your computer and use it in GitHub Desktop.
Golang StreamReader Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"crypto/aes" | |
"crypto/cipher" | |
"fmt" | |
"io" | |
"math" | |
) | |
var ( | |
AESKEY = []byte{ | |
0xE6, 0x9A, 0xB4, 0xE9, 0x9B, 0xAA, 0xE5, 0x98, | |
0x89, 0xE5, 0xB9, 0xB4, 0xE5, 0x8D, 0x8E, 0x81, | |
} | |
AesBlockCipher, _ = aes.NewCipher(AESKEY) | |
) | |
func main() { | |
var res string = `{ "ret": 0, "msg": "", "content": { "dcdn_switch": "1" } }` | |
dst := make([]byte, 16) | |
AesBlockCipher.Encrypt(dst, []byte(res)) | |
fmt.Printf("First block enc: %x\n", dst) | |
numBlocks := int(math.Ceil(float64(len(res)) / aes.BlockSize)) | |
obf := bytes.NewBuffer(make([]byte, 0, numBlocks*aes.BlockSize)) | |
obf.WriteString(res) | |
obf.Write(make([]byte, numBlocks*aes.BlockSize-obf.Len())) | |
fmt.Printf("origin: %x\n", obf.Bytes()) | |
input := obf | |
var iv [aes.BlockSize]byte | |
stream := cipher.NewOFB(AesBlockCipher, iv[:]) | |
// encryptedBytes := make([]byte, 0, numBlocks*aes.BlockSize) | |
// of, _ := os.OpenFile("encrypted-file", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) | |
// defer of.Close() | |
output := bytes.NewBuffer(nil) | |
streamWriter := &cipher.StreamWriter{S: stream, W: output} | |
io.Copy(streamWriter, input) | |
fmt.Printf("enc: %x\n len = %d\n", output.Bytes(), len(output.Bytes())) | |
d_input := bytes.NewReader(output.Bytes()) | |
d_stream := cipher.NewOFB(AesBlockCipher, iv[:]) | |
d_output := bytes.NewBuffer(nil) | |
streamReader := &cipher.StreamReader{S: d_stream, R: d_input} | |
io.Copy(d_output, streamReader) | |
fmt.Printf("dec: %x\n len = %d\n", d_output.Bytes(), len(d_output.Bytes())) | |
fmt.Printf("plain: %s\n", d_output.Bytes()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment