A Practical Implementation of the Switching Generator Using Verilog HDL


Linear feedback shift registers are an excellent tool for implementing a pseudo random bit generator in hardware; they inhibit a simple and efficient electronic structure. Further, they are capable of producing output sequences with large periods and good statistical properties. However, standard LFSRs are not cryptographically secure, since the output sequence can be uniquely predicted given a small number of key stream bits using Berlekamp-Massey algorithm. Several methods have been proposed to destroy the linearity inherent in LFSR design. These methods include nonlinear combination generators, nonlinear filter generators, and clock controlled generators. Nevertheless, they remain vulnerable to many attacks such as side channel attacks and algebraic attacks. In 2015, a new clocked controlled generator, called the switching generator, was proposed. This new generator has been proven to be resistant to algebraic attacks and side channel attacks, while preserving efficiency and security requirements. In this project, we present a design of the switching generator using Verilog HDL.

Introduction and Historical Background

The history of pseudo random number generation in hardware is heavily linked to the development of stream ciphers. Stream ciphers are ciphers that encrypt plain text characters individually (usually bit by bit), in contrast to block ciphers, which encrypt plain text in large block (64 bits or more). Many stream cipher architectures require a key stream generator, which is a pseudo random bit generator whose seed is the encryption key. For each plain text bit, the corresponding cipher text bit is calculated as some revertible function (usually xor gate) of the plain text bit and the corresponding key stream bit. Therefore, designing safe and efficient key stream generators is essential for stream cipher operation.

One useful tool for building key stream generators is linear feedback shift registers. They can be contsructed easily using elementary electronic components, and can be programmed simply on programmable logic devices. Also, due to their simple structure, LFSRs can be modeled and analyzed mathematically, which has lead to a vast body of knowledge and results regarding them. The output sequence of a correctly constructed LFSR has exponential length and good statisitical properties such as large linear complexity.

Despite the good statistical properties of the LFSR, it cannot be used as a key stream generator in its strandard form due to its linear nature. If an attacker managed to know $2L$ consecutive key stream bits, then the output sequence can be uniquely and efficiently predicted using Berlekamp-Massey algorithm, where $L$ is the number of registers. Many different ways to destroy the linearity inherent in LFSR output sequence have been proposed:

  • Using multiple LFSRs and a non-linear combining function of their outputs (non-linear combination generators).
  • Generating the output sequence as some non-linear function of the LFSR state (non-linear filter generators).
  • Irregular clocking of LFSRs (clock-controlled generators).

Still, all of these designs remained vulnerable to attacks such as algebraic and side channel attacks. After the year 2000, this was no longer a critical issue, as block cipher Rijndael was proposed and elected as the Advanced Encryption Standard (AES). AES was capable of operating in stream cipher mode and meet all industrial standards for a stream cipher. Further, with the rise of computational powers, AES could be deployed on various platforms. This has lead to a considerable decrease in stream cipher applications.

Adi Shamir presented an invited lecture in State of the Art in Stream Ciphers 2004 and Asiacrypt 2004 titled «Stream Ciphers: Dead or Alive?». In his presentation, he suggested that stream ciphers can survive in the following applications:

  • Software-oriented applications with exceptionally high speeds (e.g. routers).
  • Hardware-oriented applications with exceptionally small footprint (e.g. smart cards).

One of the latest proposals for key stream generators is the switching generator. It is claimed to be resistant to algebraic and side channel attacks, all while preserving efficiency and operating speeds.

In this project, we shall present a design of the switching generator in hardware, using Verilog HDL. First, we present the two common forms of LFSRs, Fibonacci LFSRs and Galois LFSRs. Next, we present a mathematical presentation of LFSRs. We will then present the switching generator as introduced by. Finally, we present our Verilog design of the switching generator.

Linear Feedback Shift Registers

Linear feedback shift registers are circuits consisting of a linear list of registers (also called delay elements) and a predefined set of connection among them. A global (single) clock signal controls the data flow inside the LFSR. The two most commonly used types of LFSRs are Fibonacci LFSRs and Galois LFSRs; deferring only in the form of connections. As we shall see later in the mathematical model section, there are many similarities between Fibonacci and Galois architectures, preferring one over the other is application specific.

Through out this article, we assume a hypothetical global time counter starting at $0$ and increasing by $1$ after each positive edge of the global clock cycle.


A register is a logic element capable of storing one bit of data, called the state. It has two input lines: a one bit data line and a clock signal line. It has a one-bit output that is always equal to the internal state. On every positive edge of the clock input, the data input is assigned to the state, otherwise the state remains unchanged. Let us denote the state of a register $S$ at time $t$ as $\mathop S\nolimits^t$.

Fibonacci LFSRs

A Fibonacci LFSR consists of $L$ registers enumerated from $0$ to $L-1$, all connected to the same clock signal. The input of register $i$ is the output of register $i+1$ for $0\le i \le L-2$. The feedback input for register $L-1$ is the xor sum of outputs of some subset of registers. The register update can be described mathematically as follows:

$\mathop S\nolimits_i^t = \left\{ \begin{array}{l} \mathop S\nolimits_{i + 1}^{t-1} {\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \rm{if} \ \ }0 \le i \le L-2\\ \mathop \bigoplus \limits_{j = 1}^k \mathop S\nolimits_j^{t-1} \otimes \mathop C\nolimits_j {\ \ \ \ \rm{if} \ \ }i = L-1 \end{array} \right.$

where $C_j = 1$ if register $j$ is included in the feedback and $0$ otherwise.

The output sequence is obtained from register $0$. That is, the output sequence is $\mathop {\left\{ {\mathop S\nolimits_0^i } \right\}}\nolimits_{i \ge 0} $.


Galois LFSRs

Galois LFSRs also consist of a linear list of $L$ registers enumerated from $0$ to $L-1$, all sharing the global clock signal. The input of register $i$ is the output of register $i-1$ for $1 \le i \le L-1$. For some subset of registers, their input is xored with the output of register $L-1$. This can be expressed as:

$\mathop S\nolimits_i^t = \left\{ \begin{array}{l} \mathop S\nolimits_{i-1}^{t-1} \oplus \mathop S\nolimits_{L-1}^{t-1} \otimes \mathop C\nolimits_i {\rm{\ \ \ \ if \ \ }} 1 \le i \le L-1\\ \mathop S\nolimits_{L-1}^{t-1} \otimes \mathop C\nolimits_0 {\rm{\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ if \ \ }} i = 0 \end{array} \right.$

where $C_i = 1$ if the input of register $i$ is xored with output of register $L-1$.

In a manner similar to that of Fibonacci LFSRs, the output sequence is defined as $\mathop {\left\{ {\mathop S\nolimits_{L-1}^i } \right\}}\nolimits_{i \ge 0} $.


Comparison Between Fibonacci and Galois Designs

There is a direct correspondence between Fibonacci and Galois LFSRs in the mathematical sense, as we shall see in the next section. However, there are two notable advantages of using Galois' design:
  • In software implementation, it does not require an $L$ bit parity check, which adds a logarithmic factor of complexity.
  • In hardware implementation, it only requires two-input xor gates, whose propagation delay is considerable less than that of the multi-input xor gates used in Fibonacci's design.

In our project, we consider the matrix formulation of the LFSR, so both architectures are interchangeable.

Mathematical Model of LFSRs

In the following sections, unless stated otherwise, we assume that all computation in done under Galois field $GF\left( 2 \right)$. That is, all operations are computed modulo $2$. Another realization of this convention is that all multiplication is a logical and gate, and all summation is an xor gate.

Consider the states of all $L$ registers of an LFSR at some time $t$; this can represented as a vector from ${\left\{ {0,1} \right\}^L}$:

${S^t} = \left( {\mathop S\nolimits_0^t ;\mathop S\nolimits_1^t ; \ldots ;\mathop S\nolimits_{L-1}^t } \right)$

We denote this vector as the state of the LFSR. Note that there are at most ${2^L}$ possible states for an $L$ register LFSR. Also note that if an LFSR were to reach the all-zero state, it cannot reach any other state. Therefore we say that there are $2^L-1$ non-trivial of an LFSR.

Consider the following linear transformation:

$F=\left( {\begin{array}{*{20}{c}} 0&1& \cdots &0\\ \vdots & \vdots & \ddots & \vdots \\ 0&0& \cdots &1\\ {\mathop C\nolimits_0 }&{\mathop C\nolimits_1 }& \cdots &{\mathop C\nolimits_{L-1} } \end{array}} \right)$

Given that $\mathop S\nolimits^t $ is the state of a Fibonacci LFSR, it can be observed that

$F \cdot \mathop S\nolimits^t = \mathop S\nolimits^{t + 1} $

If $\mathop S\nolimits^t $ was a state of a Galois LFSR, then consider tranformation $G$:

$G=\left( {\begin{array}{*{20}{c}} 0& \cdots &0&{\mathop C\nolimits_0 }\\ 1& \cdots &0&{\mathop C\nolimits_1 }\\ \vdots & \ddots & \vdots & \vdots \\ 0& \cdots &1&{\mathop C\nolimits_{L-1} } \end{array}} \right)$

In this case, we have

$G \cdot \mathop S\nolimits^t = \mathop S\nolimits^{t + 1} $

Matrix representations of LFSRs can be flexible when dealing with repeated updates, as they can be interpreted as a simple matrix product. It can be observed that $F = {G^T}$. This fact indicates the many similarities between Fibonacci and Galois designs if they were viewed as linear transformations from ${\left\{ {0,1} \right\}^N}$ to ${\left\{ {0,1} \right\}^N}$.

Multiplying the state vector of some LFSR by a matrix (of Fiboancci or Galois types) is known as clocking or updating the LFSR.

The Switching Generator

The Switching Generator is a clock-controlled generator proposed in 2015. It is proven to have resistance to algebraic and side channel attacks. In this section, we shall present the design of the switching generator, as specified by the its inventors.

Basic Structure

The switching generator consists of two LFSRs: a control LFSR $A$ of length $N$ and a data LFSR $B$ of length $M$. Control LFSR is updated as described previously. However, data LFSR is updated using one of two possible matrices, $\mathop M\nolimits_1^i $ or $\mathop M\nolimits_2^j $, where ${M_1},{M_2}$ are companion matrices of some primitive polynomials. Choosing one matrix over the other is determined by the signal output from the control LFSR. This process can be described as follows:

$\mathop B\nolimits^t = \left\{ \begin{array}{l} \mathop M\nolimits_1^i \cdot \mathop B\nolimits^{t-1} {\rm{\ \ \ \ if \ \ }}\mathop A\nolimits_{M-1}^t = 0\\ \mathop M\nolimits_2^j \cdot \mathop B\nolimits^{t-1} {\rm{\ \ \ \ if \ \ }}\mathop A\nolimits_{M-1}^t = 1 \end{array} \right.$

The output of the switching generator is the output of LFSR $B$. Note that we assumed that $A$ is a Galois LFSR. It can just as well be a Fibonacci LFSR.

Integers $i,j$ Are called the switching indices.

The Seed

Recall that an LFSR can iterate through at most ${2^L}-1$ non-trivial states before revisiting previous states. Since matrices ${M_1},{M_2}$ are transformation matrices of LFSRs, we can deduce that integers $i,j$ can be at most $2^M-1$ before matrices start to repeat.

The seed for the switching generator is $N + 3M$ bits, representing the initial states of the LFSRs $A$ and $B$ and the integer powers $i,j$. Note that matrices ${M_1},{M_2}$ are fixed throughout the implementation and are not included in the seed.

Verilog Design

In this section, we shall introduce our design of the switching generator using Verilog HDL. We will present every module design in a bottom up fashion. At the very end, we introduce the switching generator module.

In our design, we tried to keep synchronous components to a minimum. The only clock controlled components are the LFSRs $A,B$.

Matrix and vector operations can be implemented in a number of different methods, varying in consumption of logic units, memory units and procedural complexity. In our design, we eliminate the need for procedural blocks, and use logic elements to a maximum.

All matrices in the following modules are indexed starting at $0$ left to right, and then top to bottom.

Also note that all modules have parameterized sizes; this is for debugging purposes. In an actual implementation, all sizes are fixed.


This is a module implementing a 2 to 1 $N$-bit multiplexer. The module has two $N$-bit input lines, one 1-bit selector line, and $N$-bit output line. If the selector input is $0$ then the output is set to the first input line, otherwise it is set to the second.

Multiplexer Module

Vector Transformation

This module implements a linear transformation on a vector. It accepts as input an $N \times N$ transformation matrix and an $N$-bit vector. It outputs the matrix-vector product of its input.

Each bit in the output vector is the result of an $N$-bit xor gate, taking as input the result of the $N$-bit bitwise and of the input vector and the corresponding matrix row. That is, each output bit is hardwired to the input, and no procedural blocks are needed.

Exactly $N^2$ two-input and gates are used, along with $N$ $N$-input xor gates.

Vector Transformation Module


This module accepts no input. Its $N \times N$-bit output is initialized to the $N $ identity matrix. Such a module is declared for the sake of convenience, so that we do not have to initialize a global register vector for each different size.

Identity Matrix Module


This module accepts an $N \times N$ matrix and output its transpose. Neither logical nor memory elements are used in this module, its output is merely a permutation of its input

Matrix Transpose Module

Matrix Multiplication

This is a module implementing matrix-matrix multiplication. It accepts two $N \times N$ matrices as input, and outputs their matrix-matrix product.

This module contains an instance of the matrix transpose module. This makes it possible to assign consecutive indices to columns in the second input matrix. Each entry in the output matrix is then assigned to the output of an $N$-input xor gate, whose input is the bitwise and of the corresponding row from the first matrix and column from the second.

Exactly $N^3$ two-input and gates and $N^2$ $N$-input xor are used in this implementation.

Matrix Multiplication Module

Matrix Exponentiation

This module raises a matrix to an integer power. It accepts as input an $N \times N$ matrix and a $K$-bit integer. Its output is the matrix raised to the specified integer power.

Matrix Exponentiation Module

Control Unit

This module implements the $N$-bit control LFSR. It is one of the two clock controlled modules in our design.

It includes a static $N \times N$ LFSR transformation matrix and a variable $N$-bit state. Its input includes a clock, an $N$-bit state reset, and a reset signal. Its output is a single bit, which is the last bit of the LFSR.

After each positive edge of the clock signal, the state is updated according to the transformation matrix using a matrix-vector multiplication module. The state reset is assigned to the internal state after each positive edge of the reset signal.


Control Unit Module

Data Unit

The $N$ data LFSR is implemented using this module. Like the control unit module, it is clock controlled

The module includes two $N \times N$ transformation matrices and an $N$-bit LFSR state. It accepts as input a clock signal, a control signal, an $N$-bit LFSR state reset, two $N \times N$ matrix transformation resets, and a reset signal. It has a one bit output, the last bit of the internal LFSR.

Note that since the seed can be changed, then the transformation matrices can also be changed, unlike the control unit whose transformation matrix if fixed.


\Data Unit

The Switching Generator

This is the main module of our design. It is parameterized by integers $N,M$, which are the sizes of the control and data units, respectively.

The input to this module is a clock signal, a $N+3M$-bit seed, and a set signal. The seed is simply a concatenation of the control LFSR reset, the data LFSR reset, and integers $i,j$ Its output is one bits, the pseudo random bit generated by the switching generator.

This module includes two $M \times M$ matrices $\mathop M\nolimits_1 ,\mathop M\nolimits_2 $. These matrices are fixed throughout the implementation.

Two matrix exponentiation modules instances are used to calculate the input matrices for the data unit, where their input are the fixed transformation matrices and integers $i,j$, extracted from the seed.

The Switching Generator Module

Conclusions and Recommendations

In this project, we have presented a design of the switching generator using Verilog HDL. This design is focused entirely on hardware, and eliminates the use of procedural blocks. Such an approach allows for maximum performance at the cost of logic and memory elements. For some applications with logic and memory elements constraints, it might be beneficial to sacrifice performance and increase the use of procedural blocks to reduce electronic elements usage.

One drawback of the project it that it lays the responsibility of choosing good switching indices on the user. One possible advancement is adding a hardware component to check the validity of the used switching index. This requires a hardware implementation of complex algorithms such as finding the characteristics polynomial of a given matrix and checking it for primitivity.

A possible advancement is adding a true random number generator to check random switching indices, and outputting a valid pair once it is found. It can be proven that this process halts after a short time with high probability.


  1. Katz, Jonathan, et al. Handbook of applied cryptography. CRC press, 1996.
  2. Choi, Jun, et al. «The switching generator: New clock-controlled generator with resistance against the algebraic and side channel attacks.» Entropy 17.6 (2015): 3692-3709.
  3. Shamir, Adi. «Stream ciphers: dead or alive?.» ASIACRYPT. 2004.
  4. LFSRs for the Uninitiated

Share post

Similar posts

Comments 9

    Народ!!! FPGAшники!!! Срочно постим сюда статьи на русском! Не дадим сделать наш любимый хаб англоязычным!!! Больше статей хороших и разных!!! :)))))
      Спасибо. Интересная статья. Прочел только описание, увы, мне сейчас надо срочно убегать по делам, но тема для меня новая. Хотя когда-то я подобными генераторами интересовался.
        Похоже кто-то иностранным студентам-аспирантам показал, где можно бесплатно опубликоваться. Наврал, что публикация засчитается ВАКом ;)
          Да нет, тут в комменте к предыдущей статье камрад Exosphere просветил, что все эти ребята из Иннополиса. Нам 40 лет назад по-английски читали лекции и вели семинары по химтермодинамике. Мужики сначала ругались, потом привыкли, а дальше даже стало нравиться. Классная практика в языке. Кто знает, может и у этих ребят публикация на хабре на английском языке входит в учебный план… По мне так похер. Надо на английском, пусть пишут на английском. Лишь бы дело писали. А статьи у них вобщем-то неплохие. Эту ещё до конца не прочел (тут были дела, а по-английски я разумеется читаю не так быстро как на нашем пролетарском), но предыдущую читал с интересом. Свой первый коммент я написал в шутку, как Вы сами наверно догадываетесь :)) Хотя честно сказать опубликовать своё на родном рабоче-крестьянском, эти ребятки меня всё-таки сподвигли. Сейчас пишу.
            У нас было курсовое задание писать/переводить и доводить до избранной статьи на вики, это имхо полезнее.
              Да нет, хабр тут мне кажется всё-таки лучше. Ибо в отличии от вики тут во-первых тусуется соответствующая публика, во-вторых он куда более читаем. Что касается этих пишущих по-английски ребят, мне очень любопытно, как им выставляется оценка. По общей оценке статьи на хабре (плюсанул бы, увы кармы не хватает)? По участию в дискуссии (в предыдущей статье автор на комменты отвечает строго по-буржуйски)? А вообще очень рад, если у них препы и правда применили такой способ дрессировки. У нас 40 лет назад увы, тырнетов не было. А выступить на семинаре по химтермодинамике с каким-то интересным докладом (у нас и такое было !) на проклятом буржуинском, это для нас тогда и правда было нереально круто. Народ просто горел и рвался. Это было примерно так же круто, как на экзамен по общей физике притащить работающий эксперимент. А успешно (!!!) выступить на хабре, это по-моему ещё круче. Так что за нынешних студиозусов остаётся только порадоваться. Очень мало что меня радует в современной России, но последние здесь статьи — однозначно.
                Ну тут же никакой иерархии информации нет, нагуглилась статейка — хорошо. А вики могут многие люди улучшать и по ней можно долго ходить по ссылкам. Там можно кратенько разобраться в теме, а примеры смотреть на тематических площадках.
                  Ну как бы смотря о чем. В вики если какая-нибудь специальная статья, хрен знамо кто и хрен знамо когда её нагуглит :) А хабр я вот например просматриваю если не каждый день, то уж каждую неделю это стопудово. Особенно интересные мне хабы, такие например как FPGA. К тому же вики смотрит кто угодно, а тут (напоминаю ещё раз) в основном тусуется довольно профессиональная публика. И получить её признание уже само по себе дико круто. Вобщем будь я у этих ребятишек препом, выбрал бы всё-таки хабр, а не вику. Спросил сейчас у автора в предыдущей статье. Он ответил что да, у них типа курсач публикация статьи на хабре причем по-английски. Блин жаль кармы малою Плюсанул бы ребят обязательно.
          Поднимая вопрос генераторов случайных чисел, как правило, приводят распределение случайной величины — обычно это достаточно наглядно для восприятия.
          Утверждая, что предлагаемые реализации лучше, было бы неплохо опять же добавить некоторые характеристики сравнительные: было так стало так (пример).
          Результатом Вашей работы является не только написанный HDL-код, но и функционал, который он реализует, однако, его демонстрация отсутствует.
          Касательно способа описания реализаций различных алгоритмов на ПЛИС: на мой взгляд самый оптимальный подход применяется у capitanov — формулировка проблем, варианты решений и наглядность материала — это важнейшие составляющие подобных статей.

          Only users with full accounts can post comments. Log in, please.