issue21104_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2017 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. package crypto
  5. import (
  6. "crypto/aes"
  7. "crypto/cipher"
  8. "crypto/rc4"
  9. "testing"
  10. )
  11. func TestRC4OutOfBoundsWrite(t *testing.T) {
  12. // This cipherText is encrypted "0123456789"
  13. cipherText := []byte{238, 41, 187, 114, 151, 2, 107, 13, 178, 63}
  14. cipher, err := rc4.NewCipher([]byte{0})
  15. if err != nil {
  16. panic(err)
  17. }
  18. test(t, "RC4", cipherText, cipher.XORKeyStream)
  19. }
  20. func TestCTROutOfBoundsWrite(t *testing.T) {
  21. testBlock(t, "CTR", cipher.NewCTR)
  22. }
  23. func TestOFBOutOfBoundsWrite(t *testing.T) {
  24. testBlock(t, "OFB", cipher.NewOFB)
  25. }
  26. func TestCFBEncryptOutOfBoundsWrite(t *testing.T) {
  27. testBlock(t, "CFB Encrypt", cipher.NewCFBEncrypter)
  28. }
  29. func TestCFBDecryptOutOfBoundsWrite(t *testing.T) {
  30. testBlock(t, "CFB Decrypt", cipher.NewCFBDecrypter)
  31. }
  32. func testBlock(t *testing.T, name string, newCipher func(cipher.Block, []byte) cipher.Stream) {
  33. // This cipherText is encrypted "0123456789"
  34. cipherText := []byte{86, 216, 121, 231, 219, 191, 26, 12, 176, 117}
  35. var iv, key [16]byte
  36. block, err := aes.NewCipher(key[:])
  37. if err != nil {
  38. panic(err)
  39. }
  40. stream := newCipher(block, iv[:])
  41. test(t, name, cipherText, stream.XORKeyStream)
  42. }
  43. func test(t *testing.T, name string, cipherText []byte, xor func([]byte, []byte)) {
  44. want := "abcdefghij"
  45. plainText := []byte(want)
  46. shorterLen := len(cipherText) / 2
  47. defer func() {
  48. err := recover()
  49. if err == nil {
  50. t.Errorf("%v XORKeyStream expected to panic on len(dst) < len(src), but didn't", name)
  51. }
  52. const plain = "0123456789"
  53. if plainText[shorterLen] == plain[shorterLen] {
  54. t.Errorf("%v XORKeyStream did out of bounds write, want %v, got %v", name, want, string(plainText))
  55. }
  56. }()
  57. xor(plainText[:shorterLen], cipherText)
  58. }