C++: Main Step of GOST 28147-89


GOST 28147-89 is a standard symmetric encryption based on a Feistel network. Structure of the algorithm consists of three levels:

  1. encryption modes – simple replacement, application range, imposing a range of feedback and authentication code generation;
  2. cycles – 32-З, 32-Р and 16-З, is a repetition of the main step;
  3. main step, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8×16 matrix of 4-bit values), and returns encrypted block.

Implement the main step of this encryption algorithm.

UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)
	UINT_64 N;
	N = N1;
	N = (N<<32)|N2;
	return UINT_64(N);

UINT_32 TGost::ReplaceBlock(UINT_32 x)
	register i;
	UINT_32 res = 0UL;
		ui4_0 = x>>(i*4);
		ui4_0 = BS[ui4_0][i];
		res = (res<<4)|ui4_0;
	return res;

UINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)
	UINT_32 N1,N2,S=0UL;
	S = N1 + X % 0x4000000000000;
	S = ReplaceBlock(S);
	S = (S<<11)|(S>>21);
	S ^= N2;
	N2 = N1;
	N1 = S;
	return SWAP32(N2,N1);

Variable “BS” is the replacement table.


Content is available under GNU Free Documentation License 1.2.