]> git.ipfire.org Git - thirdparty/gcc.git/blob - libgo/go/crypto/block/ctr.go
Add Go frontend, libgo library, and Go testsuite.
[thirdparty/gcc.git] / libgo / go / crypto / block / ctr.go
1 // Copyright 2009 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 // Counter (CTR) mode.
6
7 // CTR converts a block cipher into a stream cipher by
8 // repeatedly encrypting an incrementing counter and
9 // xoring the resulting stream of data with the input.
10
11 // See NIST SP 800-38A, pp 13-15
12
13 package block
14
15 import (
16 "io"
17 )
18
19 type ctrStream struct {
20 c Cipher
21 ctr []byte
22 out []byte
23 }
24
25 func newCTRStream(c Cipher, ctr []byte) *ctrStream {
26 x := new(ctrStream)
27 x.c = c
28 x.ctr = dup(ctr)
29 x.out = make([]byte, len(ctr))
30 return x
31 }
32
33 func (x *ctrStream) Next() []byte {
34 // Next block is encryption of counter.
35 x.c.Encrypt(x.out, x.ctr)
36
37 // Increment counter
38 for i := len(x.ctr) - 1; i >= 0; i-- {
39 x.ctr[i]++
40 if x.ctr[i] != 0 {
41 break
42 }
43 }
44
45 return x.out
46 }
47
48 // NewCTRReader returns a reader that reads data from r, decrypts (or encrypts)
49 // it using c in counter (CTR) mode with the initialization vector iv.
50 // The returned Reader does not buffer and has no block size.
51 // In CTR mode, encryption and decryption are the same operation:
52 // a CTR reader applied to an encrypted stream produces a decrypted
53 // stream and vice versa.
54 func NewCTRReader(c Cipher, iv []byte, r io.Reader) io.Reader {
55 return newXorReader(newCTRStream(c, iv), r)
56 }
57
58 // NewCTRWriter returns a writer that encrypts (or decrypts) data using c
59 // in counter (CTR) mode with the initialization vector iv
60 // and writes the encrypted data to w.
61 // The returned Writer does not buffer and has no block size.
62 // In CTR mode, encryption and decryption are the same operation:
63 // a CTR writer applied to an decrypted stream produces an encrypted
64 // stream and vice versa.
65 func NewCTRWriter(c Cipher, iv []byte, w io.Writer) io.Writer {
66 return newXorWriter(newCTRStream(c, iv), w)
67 }