summaryrefslogtreecommitdiff
path: root/doc/talks/io2010/decrypt.go
blob: 0a6c006e24731d2f36c0d4641413c18811a4eb1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2010 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This code differs from the slides in that it handles errors.

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"compress/gzip"
	"io"
	"log"
	"os"
)

func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) os.Error {
	r, err := os.Open(srcfile)
	if err != nil {
		return err
	}
	var w io.Writer
	w, err = os.Create(dstfile)
	if err != nil {
		return err
	}
	c, err := aes.NewCipher(key)
	if err != nil {
		return err
	}
	w = cipher.StreamWriter{S: cipher.NewOFB(c, iv), W: w}
	w2, err := gzip.NewWriter(w)
	if err != nil {
		return err
	}
	defer w2.Close()
	_, err = io.Copy(w2, r)
	return err
}

func DecryptAndGunzip(dstfile, srcfile string, key, iv []byte) os.Error {
	f, err := os.Open(srcfile)
	if err != nil {
		return err
	}
	defer f.Close()
	c, err := aes.NewCipher(key)
	if err != nil {
		return err
	}
	r := cipher.StreamReader{S: cipher.NewOFB(c, iv), R: f}
	r2, err := gzip.NewReader(r)
	if err != nil {
		return err
	}
	w, err := os.Create(dstfile)
	if err != nil {
		return err
	}
	defer w.Close()
	_, err = io.Copy(w, r2)
	return err
}

func main() {
	err := EncryptAndGzip(
		"/tmp/passwd.gz",
		"/etc/passwd",
		make([]byte, 16),
		make([]byte, 16),
	)
	if err != nil {
		log.Fatal(err)
	}
	err = DecryptAndGunzip(
		"/dev/stdout",
		"/tmp/passwd.gz",
		make([]byte, 16),
		make([]byte, 16),
	)
	if err != nil {
		log.Fatal(err)
	}
}