...

Source file src/crypto/cipher/cipher_test.go

Documentation: crypto/cipher

		 1  // Copyright 2013 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/aes"
		10  	"crypto/cipher"
		11  	"crypto/des"
		12  	"testing"
		13  )
		14  
		15  func TestCryptBlocks(t *testing.T) {
		16  	buf := make([]byte, 16)
		17  	block, _ := aes.NewCipher(buf)
		18  
		19  	mode := cipher.NewCBCDecrypter(block, buf)
		20  	mustPanic(t, "crypto/cipher: input not full blocks", func() { mode.CryptBlocks(buf, buf[:3]) })
		21  	mustPanic(t, "crypto/cipher: output smaller than input", func() { mode.CryptBlocks(buf[:3], buf) })
		22  
		23  	mode = cipher.NewCBCEncrypter(block, buf)
		24  	mustPanic(t, "crypto/cipher: input not full blocks", func() { mode.CryptBlocks(buf, buf[:3]) })
		25  	mustPanic(t, "crypto/cipher: output smaller than input", func() { mode.CryptBlocks(buf[:3], buf) })
		26  }
		27  
		28  func mustPanic(t *testing.T, msg string, f func()) {
		29  	defer func() {
		30  		err := recover()
		31  		if err == nil {
		32  			t.Errorf("function did not panic, wanted %q", msg)
		33  		} else if err != msg {
		34  			t.Errorf("got panic %v, wanted %q", err, msg)
		35  		}
		36  	}()
		37  	f()
		38  }
		39  
		40  func TestEmptyPlaintext(t *testing.T) {
		41  	var key [16]byte
		42  	a, err := aes.NewCipher(key[:16])
		43  	if err != nil {
		44  		t.Fatal(err)
		45  	}
		46  	d, err := des.NewCipher(key[:8])
		47  	if err != nil {
		48  		t.Fatal(err)
		49  	}
		50  
		51  	s := 16
		52  	pt := make([]byte, s)
		53  	ct := make([]byte, s)
		54  	for i := 0; i < 16; i++ {
		55  		pt[i], ct[i] = byte(i), byte(i)
		56  	}
		57  
		58  	assertEqual := func(name string, got, want []byte) {
		59  		if !bytes.Equal(got, want) {
		60  			t.Fatalf("%s: got %v, want %v", name, got, want)
		61  		}
		62  	}
		63  
		64  	for _, b := range []cipher.Block{a, d} {
		65  		iv := make([]byte, b.BlockSize())
		66  		cbce := cipher.NewCBCEncrypter(b, iv)
		67  		cbce.CryptBlocks(ct, pt[:0])
		68  		assertEqual("CBC encrypt", ct, pt)
		69  
		70  		cbcd := cipher.NewCBCDecrypter(b, iv)
		71  		cbcd.CryptBlocks(ct, pt[:0])
		72  		assertEqual("CBC decrypt", ct, pt)
		73  
		74  		cfbe := cipher.NewCFBEncrypter(b, iv)
		75  		cfbe.XORKeyStream(ct, pt[:0])
		76  		assertEqual("CFB encrypt", ct, pt)
		77  
		78  		cfbd := cipher.NewCFBDecrypter(b, iv)
		79  		cfbd.XORKeyStream(ct, pt[:0])
		80  		assertEqual("CFB decrypt", ct, pt)
		81  
		82  		ctr := cipher.NewCTR(b, iv)
		83  		ctr.XORKeyStream(ct, pt[:0])
		84  		assertEqual("CTR", ct, pt)
		85  
		86  		ofb := cipher.NewOFB(b, iv)
		87  		ofb.XORKeyStream(ct, pt[:0])
		88  		assertEqual("OFB", ct, pt)
		89  	}
		90  }
		91  

View as plain text