...

Source file src/crypto/cipher/fuzz_test.go

Documentation: crypto/cipher

     1  // Copyright 2021 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  //go:build ppc64le
     6  
     7  package cipher_test
     8  
     9  import (
    10  	"bytes"
    11  	"crypto/aes"
    12  	"crypto/cipher"
    13  	"crypto/rand"
    14  	"testing"
    15  	"time"
    16  )
    17  
    18  var cbcAESFuzzTests = []struct {
    19  	name string
    20  	key  []byte
    21  }{
    22  	{
    23  		"CBC-AES128",
    24  		commonKey128,
    25  	},
    26  	{
    27  		"CBC-AES192",
    28  		commonKey192,
    29  	},
    30  	{
    31  		"CBC-AES256",
    32  		commonKey256,
    33  	},
    34  }
    35  
    36  var timeout *time.Timer
    37  
    38  const datalen = 1024
    39  
    40  func TestFuzz(t *testing.T) {
    41  
    42  	for _, ft := range cbcAESFuzzTests {
    43  		c, _ := aes.NewCipher(ft.key)
    44  
    45  		cbcAsm := cipher.NewCBCEncrypter(c, commonIV)
    46  		cbcGeneric := cipher.NewCBCGenericEncrypter(c, commonIV)
    47  
    48  		if testing.Short() {
    49  			timeout = time.NewTimer(10 * time.Millisecond)
    50  		} else {
    51  			timeout = time.NewTimer(2 * time.Second)
    52  		}
    53  
    54  		indata := make([]byte, datalen)
    55  		outgeneric := make([]byte, datalen)
    56  		outdata := make([]byte, datalen)
    57  
    58  	fuzzencrypt:
    59  		for {
    60  			select {
    61  			case <-timeout.C:
    62  				break fuzzencrypt
    63  			default:
    64  			}
    65  
    66  			rand.Read(indata[:])
    67  
    68  			cbcGeneric.CryptBlocks(indata, outgeneric)
    69  			cbcAsm.CryptBlocks(indata, outdata)
    70  
    71  			if !bytes.Equal(outdata, outgeneric) {
    72  				t.Fatalf("AES-CBC encryption does not match reference result: %x and %x, please report this error to security@golang.org", outdata, outgeneric)
    73  			}
    74  		}
    75  
    76  		cbcAsm = cipher.NewCBCDecrypter(c, commonIV)
    77  		cbcGeneric = cipher.NewCBCGenericDecrypter(c, commonIV)
    78  
    79  		if testing.Short() {
    80  			timeout = time.NewTimer(10 * time.Millisecond)
    81  		} else {
    82  			timeout = time.NewTimer(2 * time.Second)
    83  		}
    84  
    85  	fuzzdecrypt:
    86  		for {
    87  			select {
    88  			case <-timeout.C:
    89  				break fuzzdecrypt
    90  			default:
    91  			}
    92  
    93  			rand.Read(indata[:])
    94  
    95  			cbcGeneric.CryptBlocks(indata, outgeneric)
    96  			cbcAsm.CryptBlocks(indata, outdata)
    97  
    98  			if !bytes.Equal(outdata, outgeneric) {
    99  				t.Fatalf("AES-CBC decryption does not match reference result: %x and %x, please report this error to security@golang.org", outdata, outgeneric)
   100  			}
   101  		}
   102  	}
   103  }
   104  

View as plain text