require "bignum" require "table2" local pt = "Rosetta Code" print($"Plain text: : {pt}") local n = bigint.new("9516311845790656153499716760847001433441357") local e = bigint.new("65537") local d = bigint.new("5617843187844953170308463622230283376298685") local ptn = bigint.zero -- Convert plain text to a number. for {pt:byte(1, #pt)} as b do ptn = bigint.bor(bigint.shl(ptn, 8), bigint.new(b)) end if ptn >= n then print("Plain text message too long") os.exit(1) end print($"Plain text as a number : {ptn}") -- Encode a single number. local etn = bigint.modpow(ptn, e, n) print($"Encoded : {etn}") -- Decode a single number. local dtn = bigint.modpow(etn, d, n) print($"Decoded : {dtn}") -- Convert number to text. local db = table.rep(16, 0) local dx = 16 local bff = bigint.new(255) while dtn:bitlength() > 0 do db[dx] = bigint.toplain(bigint.band(dtn, bff)) dx -= 1 dtn = bigint.shr(dtn, 8) end local s = "" for i = dx + 1, 16 do s ..= string.char(db[i]) end print($"Decoded number as text : {s}")