1// Copyright 2010 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 5package cast5 6 7import ( 8 "bytes" 9 "encoding/hex" 10 "testing" 11) 12 13// This test vector is taken from RFC 2144, App B.1. 14// Since the other two test vectors are for reduced-round variants, we can't 15// use them. 16var basicTests = []struct { 17 key, plainText, cipherText string 18}{ 19 { 20 "0123456712345678234567893456789a", 21 "0123456789abcdef", 22 "238b4fe5847e44b2", 23 }, 24} 25 26func TestBasic(t *testing.T) { 27 for i, test := range basicTests { 28 key, _ := hex.DecodeString(test.key) 29 plainText, _ := hex.DecodeString(test.plainText) 30 expected, _ := hex.DecodeString(test.cipherText) 31 32 c, err := NewCipher(key) 33 if err != nil { 34 t.Errorf("#%d: failed to create Cipher: %s", i, err) 35 continue 36 } 37 var cipherText [BlockSize]byte 38 c.Encrypt(cipherText[:], plainText) 39 if !bytes.Equal(cipherText[:], expected) { 40 t.Errorf("#%d: got:%x want:%x", i, cipherText, expected) 41 } 42 43 var plainTextAgain [BlockSize]byte 44 c.Decrypt(plainTextAgain[:], cipherText[:]) 45 if !bytes.Equal(plainTextAgain[:], plainText) { 46 t.Errorf("#%d: got:%x want:%x", i, plainTextAgain, plainText) 47 } 48 } 49} 50 51// TestFull performs the test specified in RFC 2144, App B.2. 52// However, due to the length of time taken, it's disabled here and a more 53// limited version is included, below. 54func TestFull(t *testing.T) { 55 if testing.Short() { 56 // This is too slow for normal testing 57 return 58 } 59 60 a, b := iterate(1000000) 61 62 const expectedA = "eea9d0a249fd3ba6b3436fb89d6dca92" 63 const expectedB = "b2c95eb00c31ad7180ac05b8e83d696e" 64 65 if hex.EncodeToString(a) != expectedA { 66 t.Errorf("a: got:%x want:%s", a, expectedA) 67 } 68 if hex.EncodeToString(b) != expectedB { 69 t.Errorf("b: got:%x want:%s", b, expectedB) 70 } 71} 72 73func iterate(iterations int) ([]byte, []byte) { 74 const initValueHex = "0123456712345678234567893456789a" 75 76 initValue, _ := hex.DecodeString(initValueHex) 77 78 var a, b [16]byte 79 copy(a[:], initValue) 80 copy(b[:], initValue) 81 82 for i := 0; i < iterations; i++ { 83 c, _ := NewCipher(b[:]) 84 c.Encrypt(a[:8], a[:8]) 85 c.Encrypt(a[8:], a[8:]) 86 c, _ = NewCipher(a[:]) 87 c.Encrypt(b[:8], b[:8]) 88 c.Encrypt(b[8:], b[8:]) 89 } 90 91 return a[:], b[:] 92} 93 94func TestLimited(t *testing.T) { 95 a, b := iterate(1000) 96 97 const expectedA = "23f73b14b02a2ad7dfb9f2c35644798d" 98 const expectedB = "e5bf37eff14c456a40b21ce369370a9f" 99 100 if hex.EncodeToString(a) != expectedA { 101 t.Errorf("a: got:%x want:%s", a, expectedA) 102 } 103 if hex.EncodeToString(b) != expectedB { 104 t.Errorf("b: got:%x want:%s", b, expectedB) 105 } 106} 107