# OK to post homework # Alex Varjabedian, 28-Mar-2024, Homework 18 Help := proc() print(`MakeCubic(L, n)\nEncodeDES(M, K, r)\nDecodeDES(M, K, r)`) end: BinToIn:=proc(L) local k,i: k:=nops(L): add(L[i]*2^(k-i) , i=1..k): end: InToBin:=proc(n,k) local i: if ( n>=2^k or n<0) or not (type(n,integer)) then RETURN(FAIL): fi: if k=1 then if n=0 then RETURN([0]): else RETURN([1]): fi: fi: if n<2^(k-1) then RETURN([0,op(InToBin(n,k-1))]): else RETURN([1,op(InToBin(n-2^(k-1),k-1))]): fi: end: BinFun:=proc(F,L) local k: k:=nops(L): InToBin(eval(F,n=BinToIn(L)) mod 2^k,k): end: Feistel:=proc(LR,F) local k,L,R: k:=nops(LR): if k mod 2<>0 then RETURN(FAIL): fi: L:=[op(1..k/2,LR)]: R:=[op(k/2+1..k,LR)]: [op(R+ BinFun(F,L) mod 2) , op(L) ]: end: revFeistel:=proc(LR,F) local k,L,R: k:=nops(LR): if k mod 2<>0 then RETURN(FAIL): fi: L:=[op(1..k/2,LR)]: R:=[op(k/2+1..k,LR)]: [op(R), op(L + BinFun(F, R) mod 2)]: end: ############################ # ------------------------ # # PART 1 - MakeCubic(L, n) # # ------------------------ # ############################ MakeCubic := proc(L, n): if nops(L) <> 20 then return FAIL fi: return BinToIn([op(1..5,L)]) + BinToIn([op(6..10,L)])*n + BinToIn([op(11..15,L)])*n^2 + BinToIn([op(16..20,L)])*n^3: end: ############################### # --------------------------- # # PART 2 - EncodeDES(M, K, r) # # --------------------------- # ############################### print(`PART 2`); EncodeDES := proc(M, K, r) local keys, cubics, ret, i: if nops(M) mod 2 <> 0 or nops(K) <> (20*r) then return FAIL fi: keys := [seq(K[20*i-19..20*i], i = 1..r)]: cubics := [seq(MakeCubic(keys[i], n), i = 1..r)]: ret := M: for i from 1 to r do: ret := Feistel(ret, cubics[i]): od: return ret: end: # Example M := [1, 0, 0, 1, 0, 1, 1, 0, 0, 1]; K := [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; r := 1; printf("M = %a, K = %a, r = %a\n", M, K, r); printf("EncodeDES(M, K, r) = %a\n", EncodeDES(M, K, r)); ############################### # --------------------------- # # PART 3 - DecodeDES(M, K, r) # # --------------------------- # ############################### print(`PART 3`); DecodeDES := proc(M, K, r) local keys, cubics, ret, i: if nops(M) mod 2 <> 0 or nops(K) <> (20*r) then return FAIL fi: keys := [seq(K[20*i-19..20*i], i = 1..r)]: cubics := [seq(MakeCubic(keys[i], n), i = 1..r)]: ret := M: for i from r to 1 by -1 do: ret := revFeistel(ret, cubics[i]): od: return ret: end: #Example encoded := EncodeDES(M, K, r): printf("DecodeDES(%a, K, r) = %a = M\n", encoded, DecodeDES(encoded, K, r));