--- /dev/null
+// Copyright 2009 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.
+
+// Counter (CTR) mode.
+
+// CTR converts a block cipher into a stream cipher by
+// repeatedly encrypting an incrementing counter and
+// xoring the resulting stream of data with the input.
+
+// See NIST SP 800-38A, pp 13-15
+
+package block
+
+import (
+ "crypto/block";
+ "io";
+)
+
+type ctrStream struct {
+ c Cipher;
+ ctr []byte;
+ out []byte;
+}
+
+func newCTRStream(c Cipher, ctr []byte) *ctrStream {
+ x := new(ctrStream);
+ x.c = c;
+ x.ctr = copy(ctr);
+ x.out = make([]byte, len(ctr));
+ return x;
+}
+
+func (x *ctrStream) Next() []byte {
+ // Next block is encryption of counter.
+ x.c.Encrypt(x.ctr, x.out);
+
+ // Increment counter
+ for i := len(x.ctr) - 1; i >= 0; i-- {
+ x.ctr[i]++;
+ if x.ctr[i] != 0 {
+ break;
+ }
+ }
+
+ return x.out;
+}
+
+// NewCTRReader returns a reader that reads data from r, decrypts (or encrypts)
+// it using c in counter (CTR) mode with the initialization vector iv.
+// The returned Reader does not buffer and has no block size.
+// In CTR mode, encryption and decryption are the same operation:
+// a CTR reader applied to an encrypted stream produces a decrypted
+// stream and vice versa.
+func NewCTRReader(c Cipher, iv []byte, r io.Reader) io.Reader {
+ return NewXorReader(newCTRStream(c, iv), r);
+}
+
+// NewCTRWriter returns a writer that encrypts (or decrypts) data using c
+// in counter (CTR) mode with the initialization vector iv
+// and writes the encrypted data to w.
+// The returned Writer does not buffer and has no block size.
+// In CTR mode, encryption and decryption are the same operation:
+// a CTR writer applied to an decrypted stream produces an encrypted
+// stream and vice versa.
+func NewCTRWriter(c Cipher, iv []byte, w io.Writer) io.Writer {
+ return NewXorWriter(newCTRStream(c, iv), w);
+}
+
--- /dev/null
+// Copyright 2009 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.
+
+// CTR AES test vectors.
+
+// See U.S. National Institute of Standards and Technology (NIST)
+// Special Publication 800-38A, ``Recommendation for Block Cipher
+// Modes of Operation,'' 2001 Edition, pp. 55-58.
+
+package block
+
+import (
+ "crypto/aes";
+ "crypto/block";
+ "io";
+ "os";
+ "testing";
+
+ "./ecb_aes_test";
+)
+
+type ctrTest struct {
+ name string;
+ key []byte;
+ iv []byte;
+ in []byte;
+ out []byte;
+}
+
+var commonCounter = []byte {
+ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
+}
+
+var ctrAESTests = []ctrTest {
+ // NIST SP 800-38A pp 55-58
+ ctrTest {
+ "CTR-AES128",
+ commonKey128,
+ commonCounter,
+ commonInput,
+ []byte {
+ 0x87, 0x4d, 0x61, 0x91, 0xb6, 0x20, 0xe3, 0x26, 0x1b, 0xef, 0x68, 0x64, 0x99, 0x0d, 0xb6, 0xce,
+ 0x98, 0x06, 0xf6, 0x6b, 0x79, 0x70, 0xfd, 0xff, 0x86, 0x17, 0x18, 0x7b, 0xb9, 0xff, 0xfd, 0xff,
+ 0x5a, 0xe4, 0xdf, 0x3e, 0xdb, 0xd5, 0xd3, 0x5e, 0x5b, 0x4f, 0x09, 0x02, 0x0d, 0xb0, 0x3e, 0xab,
+ 0x1e, 0x03, 0x1d, 0xda, 0x2f, 0xbe, 0x03, 0xd1, 0x79, 0x21, 0x70, 0xa0, 0xf3, 0x00, 0x9c, 0xee,
+ },
+ },
+ ctrTest {
+ "CTR-AES192",
+ commonKey192,
+ commonCounter,
+ commonInput,
+ []byte {
+ 0x1a, 0xbc, 0x93, 0x24, 0x17, 0x52, 0x1c, 0xa2, 0x4f, 0x2b, 0x04, 0x59, 0xfe, 0x7e, 0x6e, 0x0b,
+ 0x09, 0x03, 0x39, 0xec, 0x0a, 0xa6, 0xfa, 0xef, 0xd5, 0xcc, 0xc2, 0xc6, 0xf4, 0xce, 0x8e, 0x94,
+ 0x1e, 0x36, 0xb2, 0x6b, 0xd1, 0xeb, 0xc6, 0x70, 0xd1, 0xbd, 0x1d, 0x66, 0x56, 0x20, 0xab, 0xf7,
+ 0x4f, 0x78, 0xa7, 0xf6, 0xd2, 0x98, 0x09, 0x58, 0x5a, 0x97, 0xda, 0xec, 0x58, 0xc6, 0xb0, 0x50,
+ },
+ },
+ ctrTest {
+ "CTR-AES256",
+ commonKey256,
+ commonCounter,
+ commonInput,
+ []byte {
+ 0x60, 0x1e, 0xc3, 0x13, 0x77, 0x57, 0x89, 0xa5, 0xb7, 0xa7, 0xf5, 0x04, 0xbb, 0xf3, 0xd2, 0x28,
+ 0xf4, 0x43, 0xe3, 0xca, 0x4d, 0x62, 0xb5, 0x9a, 0xca, 0x84, 0xe9, 0x90, 0xca, 0xca, 0xf5, 0xc5,
+ 0x2b, 0x09, 0x30, 0xda, 0xa2, 0x3d, 0xe9, 0x4c, 0xe8, 0x70, 0x17, 0xba, 0x2d, 0x84, 0x98, 0x8d,
+ 0xdf, 0xc9, 0xc5, 0x8d, 0xb6, 0x7a, 0xad, 0xa6, 0x13, 0xc2, 0xdd, 0x08, 0x45, 0x79, 0x41, 0xa6,
+ }
+ },
+}
+
+func TestCTR_AES(t *testing.T) {
+ for i, tt := range ctrAESTests {
+ test := tt.name;
+
+ c, err := aes.NewCipher(tt.key);
+ if err != nil {
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err);
+ continue;
+ }
+
+ for j := 0; j <= 5; j += 5 {
+ var crypt io.ByteBuffer;
+ in := tt.in[0:len(tt.in) - j];
+ w := block.NewCTRWriter(c, tt.iv, &crypt);
+ var r io.Reader = io.NewByteReader(in);
+ n, err := io.Copy(r, w);
+ if n != int64(len(in)) || err != nil {
+ t.Errorf("%s/%d: CTRWriter io.Copy = %d, %v want %d, nil", test, len(in), n, err, len(in));
+ } else if d, out := crypt.Data(), tt.out[0:len(in)]; !same(out, d) {
+ t.Errorf("%s/%d: CTRWriter\ninpt %x\nhave %x\nwant %x", test, len(in), in, d, out);
+ }
+ }
+
+ for j := 0; j <= 7; j += 7 {
+ var plain io.ByteBuffer;
+ out := tt.out[0:len(tt.out) - j];
+ r := block.NewCTRReader(c, tt.iv, io.NewByteReader(out));
+ w := &plain;
+ n, err := io.Copy(r, w);
+ if n != int64(len(out)) || err != nil {
+ t.Errorf("%s/%d: CTRReader io.Copy = %d, %v want %d, nil", test, len(out), n, err, len(out));
+ } else if d, in := plain.Data(), tt.in[0:len(out)]; !same(in, d) {
+ t.Errorf("%s/%d: CTRReader\nhave %x\nwant %x", test, len(out), d, in);
+ }
+ }
+
+ if t.Failed() {
+ break;
+ }
+ }
+}
--- /dev/null
+// Copyright 2009 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.
+
+// Output feedback (OFB) mode.
+
+// OFB converts a block cipher into a stream cipher by
+// repeatedly encrypting an initialization vector and
+// xoring the resulting stream of data with the input.
+
+// See NIST SP 800-38A, pp 13-15
+
+package block
+
+import (
+ "crypto/block";
+ "io";
+)
+
+type ofbStream struct {
+ c Cipher;
+ iv []byte;
+}
+
+func newOFBStream(c Cipher, iv []byte) *ofbStream {
+ x := new(ofbStream);
+ x.c = c;
+ n := len(iv);
+ if n != c.BlockSize() {
+ panicln("crypto/block: newOFBStream: invalid iv size", n, "!=", c.BlockSize());
+ }
+ x.iv = copy(iv);
+ return x;
+}
+
+func (x *ofbStream) Next() []byte {
+ x.c.Encrypt(x.iv, x.iv);
+ return x.iv;
+}
+
+// NewOFBReader returns a reader that reads data from r, decrypts (or encrypts)
+// it using c in output feedback (OFB) mode with the initialization vector iv.
+// The returned Reader does not buffer and has no block size.
+// In OFB mode, encryption and decryption are the same operation:
+// an OFB reader applied to an encrypted stream produces a decrypted
+// stream and vice versa.
+func NewOFBReader(c Cipher, iv []byte, r io.Reader) io.Reader {
+ return NewXorReader(newOFBStream(c, iv), r);
+}
+
+// NewOFBWriter returns a writer that encrypts (or decrypts) data using c
+// in cipher feedback (OFB) mode with the initialization vector iv
+// and writes the encrypted data to w.
+// The returned Writer does not buffer and has no block size.
+// In OFB mode, encryption and decryption are the same operation:
+// an OFB writer applied to an decrypted stream produces an encrypted
+// stream and vice versa.
+func NewOFBWriter(c Cipher, iv []byte, w io.Writer) io.Writer {
+ return NewXorWriter(newOFBStream(c, iv), w);
+}
+
--- /dev/null
+// Copyright 2009 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.
+
+// OFB AES test vectors.
+
+// See U.S. National Institute of Standards and Technology (NIST)
+// Special Publication 800-38A, ``Recommendation for Block Cipher
+// Modes of Operation,'' 2001 Edition, pp. 52-55.
+
+package block
+
+// gotest: $GC ecb_aes_test.go
+
+import (
+ "crypto/aes";
+ "crypto/block";
+ "io";
+ "os";
+ "testing";
+
+ "./ecb_aes_test";
+)
+
+type ofbTest struct {
+ name string;
+ key []byte;
+ iv []byte;
+ in []byte;
+ out []byte;
+}
+
+var ofbAESTests = []ofbTest {
+ // NIST SP 800-38A pp 52-55
+ ofbTest {
+ "OFB-AES128",
+ commonKey128,
+ commonIV,
+ commonInput,
+ []byte {
+ 0x3b, 0x3f, 0xd9, 0x2e, 0xb7, 0x2d, 0xad, 0x20, 0x33, 0x34, 0x49, 0xf8, 0xe8, 0x3c, 0xfb, 0x4a,
+ 0x77, 0x89, 0x50, 0x8d, 0x16, 0x91, 0x8f, 0x03, 0xf5, 0x3c, 0x52, 0xda, 0xc5, 0x4e, 0xd8, 0x25,
+ 0x97, 0x40, 0x05, 0x1e, 0x9c, 0x5f, 0xec, 0xf6, 0x43, 0x44, 0xf7, 0xa8, 0x22, 0x60, 0xed, 0xcc,
+ 0x30, 0x4c, 0x65, 0x28, 0xf6, 0x59, 0xc7, 0x78, 0x66, 0xa5, 0x10, 0xd9, 0xc1, 0xd6, 0xae, 0x5e,
+ },
+ },
+ ofbTest {
+ "OFB-AES192",
+ commonKey192,
+ commonIV,
+ commonInput,
+ []byte {
+ 0xcd, 0xc8, 0x0d, 0x6f, 0xdd, 0xf1, 0x8c, 0xab, 0x34, 0xc2, 0x59, 0x09, 0xc9, 0x9a, 0x41, 0x74,
+ 0xfc, 0xc2, 0x8b, 0x8d, 0x4c, 0x63, 0x83, 0x7c, 0x09, 0xe8, 0x17, 0x00, 0xc1, 0x10, 0x04, 0x01,
+ 0x8d, 0x9a, 0x9a, 0xea, 0xc0, 0xf6, 0x59, 0x6f, 0x55, 0x9c, 0x6d, 0x4d, 0xaf, 0x59, 0xa5, 0xf2,
+ 0x6d, 0x9f, 0x20, 0x08, 0x57, 0xca, 0x6c, 0x3e, 0x9c, 0xac, 0x52, 0x4b, 0xd9, 0xac, 0xc9, 0x2a,
+ },
+ },
+ ofbTest {
+ "OFB-AES256",
+ commonKey256,
+ commonIV,
+ commonInput,
+ []byte {
+ 0xdc, 0x7e, 0x84, 0xbf, 0xda, 0x79, 0x16, 0x4b, 0x7e, 0xcd, 0x84, 0x86, 0x98, 0x5d, 0x38, 0x60,
+ 0x4f, 0xeb, 0xdc, 0x67, 0x40, 0xd2, 0x0b, 0x3a, 0xc8, 0x8f, 0x6a, 0xd8, 0x2a, 0x4f, 0xb0, 0x8d,
+ 0x71, 0xab, 0x47, 0xa0, 0x86, 0xe8, 0x6e, 0xed, 0xf3, 0x9d, 0x1c, 0x5b, 0xba, 0x97, 0xc4, 0x08,
+ 0x01, 0x26, 0x14, 0x1d, 0x67, 0xf3, 0x7b, 0xe8, 0x53, 0x8f, 0x5a, 0x8b, 0xe7, 0x40, 0xe4, 0x84,
+ }
+ },
+}
+
+func TestOFB_AES(t *testing.T) {
+ for i, tt := range ofbAESTests {
+ test := tt.name;
+
+ c, err := aes.NewCipher(tt.key);
+ if err != nil {
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err);
+ continue;
+ }
+
+ for j := 0; j <= 5; j += 5 {
+ var crypt io.ByteBuffer;
+ in := tt.in[0:len(tt.in) - j];
+ w := NewOFBWriter(c, tt.iv, &crypt);
+ var r io.Reader = io.NewByteReader(in);
+ n, err := io.Copy(r, w);
+ if n != int64(len(in)) || err != nil {
+ t.Errorf("%s/%d: OFBWriter io.Copy = %d, %v want %d, nil", test, len(in), n, err, len(in));
+ } else if d, out := crypt.Data(), tt.out[0:len(in)]; !same(out, d) {
+ t.Errorf("%s/%d: OFBWriter\ninpt %x\nhave %x\nwant %x", test, len(in), in, d, out);
+ }
+ }
+
+ for j := 0; j <= 7; j += 7 {
+ var plain io.ByteBuffer;
+ out := tt.out[0:len(tt.out) - j];
+ r := NewOFBReader(c, tt.iv, io.NewByteReader(out));
+ w := &plain;
+ n, err := io.Copy(r, w);
+ if n != int64(len(out)) || err != nil {
+ t.Errorf("%s/%d: OFBReader io.Copy = %d, %v want %d, nil", test, len(out), n, err, len(out));
+ } else if d, in := plain.Data(), tt.in[0:len(out)]; !same(in, d) {
+ t.Errorf("%s/%d: OFBReader\nhave %x\nwant %x", test, len(out), d, in);
+ }
+ }
+
+ if t.Failed() {
+ break;
+ }
+ }
+}
--- /dev/null
+// Copyright 2009 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.
+
+// Encrypt/decrypt data by xor with a pseudo-random data stream.
+
+package block
+
+import (
+ "crypto/block";
+ "io";
+ "os";
+)
+
+type DataStream interface {
+ Next() []byte
+}
+
+type xorReader struct {
+ r io.Reader;
+ rand DataStream; // pseudo-random
+ buf []byte; // data available from last call to rand
+}
+
+func NewXorReader(rand DataStream, r io.Reader) io.Reader {
+ x := new(xorReader);
+ x.r = r;
+ x.rand = rand;
+ return x;
+}
+
+func (x *xorReader) Read(p []byte) (n int, err os.Error) {
+ n, err = x.r.Read(p);
+
+ // xor input with stream.
+ bp := 0;
+ buf := x.buf;
+ for i := 0; i < n; i++ {
+ if bp >= len(buf) {
+ buf = x.rand.Next();
+ bp = 0;
+ }
+ p[i] ^= buf[bp];
+ bp++;
+ }
+ x.buf = buf[bp:len(buf)];
+ return n, err;
+}
+
+type xorWriter struct {
+ w io.Writer;
+ rand DataStream; // pseudo-random
+ buf []byte; // last buffer returned by rand
+ extra []byte; // extra random data (use before buf)
+ work []byte; // work space
+}
+
+func NewXorWriter(rand DataStream, w io.Writer) io.Writer {
+ x := new(xorWriter);
+ x.w = w;
+ x.rand = rand;
+ x.work = make([]byte, 4096);
+ return x;
+}
+
+func (x *xorWriter) Write(p []byte) (n int, err os.Error) {
+ for len(p) > 0 {
+ // Determine next chunk of random data
+ // and xor with p into x.work.
+ var chunk []byte;
+ m := len(p);
+ if nn := len(x.extra); nn > 0 {
+ // extra points into work, so edit directly
+ if m > nn {
+ m = nn;
+ }
+ for i := 0; i < m; i++ {
+ x.extra[i] ^= p[i];
+ }
+ chunk = x.extra[0:m];
+ } else {
+ // xor p ^ buf into work, refreshing buf as needed
+ if nn := len(x.work); m > nn {
+ m = nn;
+ }
+ bp := 0;
+ buf := x.buf;
+ for i := 0; i < m; i++ {
+ if bp >= len(buf) {
+ buf = x.rand.Next();
+ bp = 0;
+ }
+ x.work[i] = buf[bp] ^ p[i];
+ bp++;
+ }
+ x.buf = buf[bp:len(buf)];
+ chunk = x.work[0:m];
+ }
+
+ // Write chunk.
+ var nn int;
+ nn, err = x.w.Write(chunk);
+ if nn != len(chunk) && err == nil {
+ err = io.ErrShortWrite;
+ }
+ if nn < len(chunk) {
+ // Reconstruct the random bits from the unwritten
+ // data and save them for next time.
+ for i := nn; i < m; i++ {
+ chunk[i] ^= p[i];
+ }
+ x.extra = chunk[nn:len(chunk)];
+ }
+ n += nn;
+ if err != nil {
+ return;
+ }
+ p = p[m:len(p)];
+ }
+ return;
+}
+
--- /dev/null
+// Copyright 2009 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.
+
+package block
+
+import (
+ "crypto/block";
+ "fmt";
+ "io";
+ "testing";
+ "testing/iotest";
+)
+
+// Simple "pseudo-random" stream for testing.
+type incStream struct {
+ buf []byte;
+ n byte;
+}
+
+func newIncStream(blockSize int) *incStream {
+ x := new(incStream);
+ x.buf = make([]byte, blockSize);
+ return x;
+}
+
+func (x *incStream) Next() []byte {
+ x.n++;
+ for i := range x.buf {
+ x.buf[i] = x.n;
+ x.n++;
+ }
+ return x.buf;
+}
+
+func testXorWriter(t *testing.T, maxio int) {
+ var plain, crypt [256]byte;
+ for i := 0; i < len(plain); i++ {
+ plain[i] = byte(i);
+ }
+ b := new(io.ByteBuffer);
+ for block := 1; block <= 64 && block <= maxio; block *= 2 {
+ // compute encrypted version
+ n := byte(0);
+ for i := 0; i < len(crypt); i++ {
+ if i % block == 0 {
+ n++;
+ }
+ crypt[i] = plain[i] ^ n;
+ n++;
+ }
+
+ for frag := 0; frag < 2; frag++ {
+ test := fmt.Sprintf("block=%d frag=%d maxio=%d", block, frag, maxio);
+ b.Reset();
+ r := io.NewByteReader(&plain);
+ s := newIncStream(block);
+ w := NewXorWriter(s, b);
+
+ // copy plain into w in increasingly large chunks: 1, 1, 2, 4, 8, ...
+ // if frag != 0, move the 1 to the end to cause fragmentation.
+ if frag == 0 {
+ nn, err := io.Copyn(r, w, 1);
+ if err != nil {
+ t.Errorf("%s: first Copyn: %s", test, err);
+ continue;
+ }
+ }
+ for n := 1; n <= len(plain)/2; n *= 2 {
+ nn, err := io.Copyn(r, w, int64(n));
+ if err != nil {
+ t.Errorf("%s: Copyn %d: %s", test, n, err);
+ }
+ }
+
+ // check output
+ crypt := crypt[0:len(crypt) - frag];
+ data := b.Data();
+ if len(data) != len(crypt) {
+ t.Errorf("%s: want %d bytes, got %d", test, len(crypt), len(data));
+ continue;
+ }
+
+ if string(data) != string(crypt) {
+ t.Errorf("%s: want %x got %x", test, data, crypt);
+ }
+ }
+ }
+}
+
+
+func TestXorWriter(t *testing.T) {
+ // Do shorter I/O sizes first; they're easier to debug.
+ for n := 1; n <= 256 && !t.Failed(); n *= 2 {
+ testXorWriter(t, n);
+ }
+}
+
+func testXorReader(t *testing.T, maxio int) {
+ var readers = []func(io.Reader) io.Reader {
+ func (r io.Reader) io.Reader { return r },
+ iotest.OneByteReader,
+ iotest.HalfReader,
+ };
+ var plain, crypt [256]byte;
+ for i := 0; i < len(plain); i++ {
+ plain[i] = byte(255 - i);
+ }
+ b := new(io.ByteBuffer);
+ for block := 1; block <= 64 && block <= maxio; block *= 2 {
+ // compute encrypted version
+ n := byte(0);
+ for i := 0; i < len(crypt); i++ {
+ if i % block == 0 {
+ n++;
+ }
+ crypt[i] = plain[i] ^ n;
+ n++;
+ }
+
+ for mode := 0; mode < len(readers); mode++ {
+ for frag := 0; frag < 2; frag++ {
+ test := fmt.Sprintf("block=%d mode=%d frag=%d maxio=%d", block, mode, frag, maxio);
+ s := newIncStream(block);
+ b.Reset();
+ r := NewXorReader(s, readers[mode](io.NewByteReader(crypt[0:maxio])));
+
+ // read from crypt in increasingly large chunks: 1, 1, 2, 4, 8, ...
+ // if frag == 1, move the 1 to the end to cause fragmentation.
+ if frag == 0 {
+ nn, err := io.Copyn(r, b, 1);
+ if err != nil {
+ t.Errorf("%s: first Copyn: %s", test, err);
+ continue;
+ }
+ }
+ for n := 1; n <= maxio/2; n *= 2 {
+ nn, err := io.Copyn(r, b, int64(n));
+ if err != nil {
+ t.Errorf("%s: Copyn %d: %s", test, n, err);
+ }
+ }
+
+ // check output
+ data := b.Data();
+ crypt := crypt[0:maxio - frag];
+ plain := plain[0:maxio - frag];
+ if len(data) != len(plain) {
+ t.Errorf("%s: want %d bytes, got %d", test, len(plain), len(data));
+ continue;
+ }
+
+ if string(data) != string(plain) {
+ t.Errorf("%s: input=%x want %x got %x", test, crypt, plain, data);
+ }
+ }
+ }
+ }
+}
+
+func TestXorReader(t *testing.T) {
+ // Do shorter I/O sizes first; they're easier to debug.
+ for n := 1; n <= 256 && !t.Failed(); n *= 2 {
+ testXorReader(t, n);
+ }
+}
+
+// TODO(rsc): Test handling of writes after write errors.
+