2
$\begingroup$

I have a function that generates cipher text for ElGamal encryption and I want to make return two values, but it returns only one. This is the code:

elgamalencrypt[m_, p_, g_, h_] := Module[{k, r, t},
SeedRandom[];
k = RandomInteger[{2,p-2}]; 
r = PowerMod[g,k,p] ; 
t = Mod[Power[h,k]*m,p] ;
Return [{r,t},Module];
]

I tried modifying the Return statement to: Return [{r,t}] and Return [r,t], but I was keep getting an error about not enclosing the function, also tried this Break::nofunc Continue::nofunc Return::nofunc from documentation with no luck. If someone wants to try it out this is a test scenario:

plaintext = toblocks["whataboutsecondbreakfast",3] this divides the plain text into blocks {230801,200102,152120,190503,151404,21805,11106,11920} output

{p, g, h} = getelgamalpublickey[33] generate the values for the public key

{22822153,8469268,20935791} output

ciphertext =Map[elgamalencrypt[#,p,g,h]&,plaintext] and finally the encryption of each block {18627519,22660971,10034668,14492011,14579397,12595172,4596731,20282426} output

In the last output I want to have both r and t as result, how can I achieve that?

$\endgroup$
2
  • $\begingroup$ It is always helpful & recommended to include the definition of any necessary sub function you want to get help with, such as your toblocks; though, here, it does not seem to be entirely necessary. $\endgroup$ Commented Jun 5, 2021 at 21:59
  • $\begingroup$ For me your code works alright when using the values for plaintext and p,g,h as you describe (but gives different results). Can you try this with a fresh kernel? Nevertheless, as mikado shows the final Return is not needed in Mathematica, and it is best practice to avoid it. $\endgroup$ Commented Jun 6, 2021 at 8:15

1 Answer 1

7
$\begingroup$

You almost have this correct (I think). You don't need to use Return (check the documentation, it doesn't do what you think).

The result of a module is simply the last value (more accurately, everything to the left of each ; is discarded).

So having defined

elgamalencrypt[m_, p_, g_, h_] := 
 Module[{k, r, t}, SeedRandom[];
  k = RandomInteger[{2, p - 2}];
  r = PowerMod[g, k, p];
  t = Mod[Power[h, k]*m, p];
  {r, t}]


plaintext = {230801, 200102, 152120, 190503, 151404, 21805, 
  11106, 11920}
(* {230801, 200102, 152120, 190503, 151404, 21805, 11106, 11920} *)

{p, g, h} = {22822153, 8469268, 20935791}
(* {22822153, 8469268, 20935791} *)

you can make the call you want

ciphertext = Map[elgamalencrypt[#, p, g, h] &, plaintext]
(* {{6332963, 18176522}, {11878596, 18057113}, {832919, 
  18591539}, {9726226, 11069498}, {630979, 22520507}, {11489832, 
  2457708}, {6108168, 5897594}, {14498023, 4642761}} *)
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.