Black Lives Matter. Support the Equal Justice Initiative.

Source file src/crypto/cipher/xor_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/cipher"
    10  	"crypto/rand"
    11  	"fmt"
    12  	"io"
    13  	"testing"
    14  )
    15  
    16  func TestXOR(t *testing.T) {
    17  	for j := 1; j <= 1024; j++ {
    18  		if testing.Short() && j > 16 {
    19  			break
    20  		}
    21  		for alignP := 0; alignP < 2; alignP++ {
    22  			for alignQ := 0; alignQ < 2; alignQ++ {
    23  				for alignD := 0; alignD < 2; alignD++ {
    24  					p := make([]byte, j)[alignP:]
    25  					q := make([]byte, j)[alignQ:]
    26  					d1 := make([]byte, j+alignD)[alignD:]
    27  					d2 := make([]byte, j+alignD)[alignD:]
    28  					if _, err := io.ReadFull(rand.Reader, p); err != nil {
    29  						t.Fatal(err)
    30  					}
    31  					if _, err := io.ReadFull(rand.Reader, q); err != nil {
    32  						t.Fatal(err)
    33  					}
    34  					cipher.XorBytes(d1, p, q)
    35  					n := min(p, q)
    36  					for i := 0; i < n; i++ {
    37  						d2[i] = p[i] ^ q[i]
    38  					}
    39  					if !bytes.Equal(d1, d2) {
    40  						t.Logf("p: %#v", p)
    41  						t.Logf("q: %#v", q)
    42  						t.Logf("expect: %#v", d2)
    43  						t.Logf("result: %#v", d1)
    44  						t.Fatal("not equal")
    45  					}
    46  				}
    47  			}
    48  		}
    49  	}
    50  }
    51  
    52  func min(a, b []byte) int {
    53  	n := len(a)
    54  	if len(b) < n {
    55  		n = len(b)
    56  	}
    57  	return n
    58  }
    59  
    60  func BenchmarkXORBytes(b *testing.B) {
    61  	dst := make([]byte, 1<<15)
    62  	data0 := make([]byte, 1<<15)
    63  	data1 := make([]byte, 1<<15)
    64  	sizes := []int64{1 << 3, 1 << 7, 1 << 11, 1 << 15}
    65  	for _, size := range sizes {
    66  		b.Run(fmt.Sprintf("%dBytes", size), func(b *testing.B) {
    67  			s0 := data0[:size]
    68  			s1 := data1[:size]
    69  			b.SetBytes(int64(size))
    70  			for i := 0; i < b.N; i++ {
    71  				cipher.XorBytes(dst, s0, s1)
    72  			}
    73  		})
    74  	}
    75  }
    76  

View as plain text