Source file src/crypto/cipher/cbc_test.go

     1  // Copyright 2024 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  	"crypto/aes"
     9  	"crypto/cipher"
    10  	"crypto/des"
    11  	"crypto/internal/cryptotest"
    12  	"fmt"
    13  	"io"
    14  	"math/rand"
    15  	"testing"
    16  	"time"
    17  )
    18  
    19  // Test CBC Blockmode against the general cipher.BlockMode interface tester
    20  func TestCBCBlockMode(t *testing.T) {
    21  	cryptotest.TestAllImplementations(t, "aes", func(t *testing.T) {
    22  		for _, keylen := range []int{128, 192, 256} {
    23  			t.Run(fmt.Sprintf("AES-%d", keylen), func(t *testing.T) {
    24  				rng := newRandReader(t)
    25  
    26  				key := make([]byte, keylen/8)
    27  				rng.Read(key)
    28  
    29  				block, err := aes.NewCipher(key)
    30  				if err != nil {
    31  					panic(err)
    32  				}
    33  
    34  				cryptotest.TestBlockMode(t, block, cipher.NewCBCEncrypter, cipher.NewCBCDecrypter)
    35  			})
    36  		}
    37  	})
    38  
    39  	t.Run("DES", func(t *testing.T) {
    40  		rng := newRandReader(t)
    41  
    42  		key := make([]byte, 8)
    43  		rng.Read(key)
    44  
    45  		block, err := des.NewCipher(key)
    46  		if err != nil {
    47  			panic(err)
    48  		}
    49  
    50  		cryptotest.TestBlockMode(t, block, cipher.NewCBCEncrypter, cipher.NewCBCDecrypter)
    51  	})
    52  }
    53  
    54  func newRandReader(t *testing.T) io.Reader {
    55  	seed := time.Now().UnixNano()
    56  	t.Logf("Deterministic RNG seed: 0x%x", seed)
    57  	return rand.New(rand.NewSource(seed))
    58  }
    59  

View as plain text