github.com/geph-official/geph2@v0.22.6-0.20210211030601-f527cb59b0df/libs/kcp-go/entropy.go (about)

     1  package kcp
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"crypto/md5"
     7  	"crypto/rand"
     8  	"io"
     9  )
    10  
    11  // Entropy defines a entropy source
    12  type Entropy interface {
    13  	Init()
    14  	Fill(nonce []byte)
    15  }
    16  
    17  // nonceMD5 nonce generator for packet header
    18  type nonceMD5 struct {
    19  	seed [md5.Size]byte
    20  }
    21  
    22  func (n *nonceMD5) Init() { /*nothing required*/ }
    23  
    24  func (n *nonceMD5) Fill(nonce []byte) {
    25  	if n.seed[0] == 0 { // entropy update
    26  		io.ReadFull(rand.Reader, n.seed[:])
    27  	}
    28  	n.seed = md5.Sum(n.seed[:])
    29  	copy(nonce, n.seed[:])
    30  }
    31  
    32  // nonceAES128 nonce generator for packet headers
    33  type nonceAES128 struct {
    34  	seed  [aes.BlockSize]byte
    35  	block cipher.Block
    36  }
    37  
    38  func (n *nonceAES128) Init() {
    39  	var key [16]byte //aes-128
    40  	io.ReadFull(rand.Reader, key[:])
    41  	io.ReadFull(rand.Reader, n.seed[:])
    42  	block, _ := aes.NewCipher(key[:])
    43  	n.block = block
    44  }
    45  
    46  func (n *nonceAES128) Fill(nonce []byte) {
    47  	if n.seed[0] == 0 { // entropy update
    48  		io.ReadFull(rand.Reader, n.seed[:])
    49  	}
    50  	n.block.Encrypt(n.seed[:], n.seed[:])
    51  	copy(nonce, n.seed[:])
    52  }