...

Source file src/crypto/cipher/ctr_test.go

Documentation: crypto/cipher

		 1  // Copyright 2015 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  package cipher_test
		 6  
		 7  import (
		 8  	"bytes"
		 9  	"crypto/cipher"
		10  	"testing"
		11  )
		12  
		13  type noopBlock int
		14  
		15  func (b noopBlock) BlockSize() int				{ return int(b) }
		16  func (noopBlock) Encrypt(dst, src []byte) { copy(dst, src) }
		17  func (noopBlock) Decrypt(dst, src []byte) { copy(dst, src) }
		18  
		19  func inc(b []byte) {
		20  	for i := len(b) - 1; i >= 0; i++ {
		21  		b[i]++
		22  		if b[i] != 0 {
		23  			break
		24  		}
		25  	}
		26  }
		27  
		28  func xor(a, b []byte) {
		29  	for i := range a {
		30  		a[i] ^= b[i]
		31  	}
		32  }
		33  
		34  func TestCTR(t *testing.T) {
		35  	for size := 64; size <= 1024; size *= 2 {
		36  		iv := make([]byte, size)
		37  		ctr := cipher.NewCTR(noopBlock(size), iv)
		38  		src := make([]byte, 1024)
		39  		for i := range src {
		40  			src[i] = 0xff
		41  		}
		42  		want := make([]byte, 1024)
		43  		copy(want, src)
		44  		counter := make([]byte, size)
		45  		for i := 1; i < len(want)/size; i++ {
		46  			inc(counter)
		47  			xor(want[i*size:(i+1)*size], counter)
		48  		}
		49  		dst := make([]byte, 1024)
		50  		ctr.XORKeyStream(dst, src)
		51  		if !bytes.Equal(dst, want) {
		52  			t.Errorf("for size %d\nhave %x\nwant %x", size, dst, want)
		53  		}
		54  	}
		55  }
		56  

View as plain text