GOST 28147-89 is a standard symmetric encryption based on a Feistel network.



The structure of the algorithm consists of three levels:

   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
   cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
   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 (8x16 matrix of 4-bit values), and returns encrypted block.


Task

Implement the main step of this encryption algorithm.




Dim Shared As Ubyte k87(255), k65(255), k43(255), k21(255)
 
Sub kboxinit()
    Dim As Ubyte k8(15) = {14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7} 
    Dim As Ubyte k7(15) = {15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10}
    Dim As Ubyte k6(15) = {10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8}
    Dim As Ubyte k5(15) = { 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15}
    Dim As Ubyte k4(15) = { 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9}
    Dim As Ubyte k3(15) = {12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11}
    Dim As Ubyte k2(15) = { 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1}
    Dim As Ubyte k1(15) = {13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7}
 
    For i As Uinteger = 0 To 255
	k87(i) = k8(i Shr 4) Shl 4 Or k7(i And 15)
	k65(i) = k6(i Shr 4) Shl 4 Or k5(i And 15)
	k43(i) = k4(i Shr 4) Shl 4 Or k3(i And 15)
	k21(i) = k2(i Shr 4) Shl 4 Or k1(i And 15)
    Next i
End Sub
 
Function f(x As Integer) As Integer
    x =  k87(x Shr 24 And 255) Shl 24 Or k65(x Shr  16 And 255) Shl 16 Or _
         k43(x Shr  8 And 255) Shl  8 Or k21(x And 255)
    Return x Shl 11 Or x Shr (32-11)
End Function