github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2010/io/decrypt.go (about)

     1  // Copyright 2010 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build OMIT
     6  
     7  // This code differs from the slides in that it handles errors.
     8  
     9  package main
    10  
    11  import (
    12  	"compress/gzip"
    13  	"crypto/aes"
    14  	"crypto/cipher"
    15  	"io"
    16  	"log"
    17  	"os"
    18  )
    19  
    20  func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) error {
    21  	r, err := os.Open(srcfile)
    22  	if err != nil {
    23  		return err
    24  	}
    25  	var w io.Writer
    26  	w, err = os.Create(dstfile)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	c, err := aes.NewCipher(key)
    31  	if err != nil {
    32  		return err
    33  	}
    34  	w = cipher.StreamWriter{S: cipher.NewOFB(c, iv), W: w}
    35  	w2, err := gzip.NewWriter(w)
    36  	if err != nil {
    37  		return err
    38  	}
    39  	defer w2.Close()
    40  	_, err = io.Copy(w2, r)
    41  	return err
    42  }
    43  
    44  func DecryptAndGunzip(dstfile, srcfile string, key, iv []byte) error {
    45  	f, err := os.Open(srcfile)
    46  	if err != nil {
    47  		return err
    48  	}
    49  	defer f.Close()
    50  	c, err := aes.NewCipher(key)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	r := cipher.StreamReader{S: cipher.NewOFB(c, iv), R: f}
    55  	r2, err := gzip.NewReader(r)
    56  	if err != nil {
    57  		return err
    58  	}
    59  	w, err := os.Create(dstfile)
    60  	if err != nil {
    61  		return err
    62  	}
    63  	defer w.Close()
    64  	_, err = io.Copy(w, r2)
    65  	return err
    66  }
    67  
    68  func main() {
    69  	err := EncryptAndGzip(
    70  		"/tmp/passwd.gz",
    71  		"/etc/passwd",
    72  		make([]byte, 16),
    73  		make([]byte, 16),
    74  	)
    75  	if err != nil {
    76  		log.Fatal(err)
    77  	}
    78  	err = DecryptAndGunzip(
    79  		"/dev/stdout",
    80  		"/tmp/passwd.gz",
    81  		make([]byte, 16),
    82  		make([]byte, 16),
    83  	)
    84  	if err != nil {
    85  		log.Fatal(err)
    86  	}
    87  }