Skip to content

Commit 2a97f46

Browse files
committed
Use binary conversion function in RSA example
1 parent 2ff5e58 commit 2a97f46

File tree

2 files changed

+4
-26
lines changed

2 files changed

+4
-26
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ For more usage examples check the
8585
Some interesting examples there:
8686

8787
* [factorial.lua](https://github.com/edubart/lua-bint/blob/master/examples/factorial.lua) - calculate factorial of 100
88-
* [fibonacci.lua](https://github.com/edubart/lua-bint/blob/master/examples/fiboncaci.lua) - calculate the 1001th number of the Fibonacci sequence
88+
* [fibonacci.lua](https://github.com/edubart/lua-bint/blob/master/examples/fibonacci.lua) - calculate the 1001th number of the Fibonacci sequence
8989
* [pi.lua](https://github.com/edubart/lua-bint/blob/master/examples/pi.lua) - calculate the first 100 digits of Pi
9090
* [e.lua](https://github.com/edubart/lua-bint/blob/master/examples/e.lua) - calculate the first 100 digits of Euler's number
9191
* [rsa.lua](https://github.com/edubart/lua-bint/blob/master/examples/rsa.lua) - simple RSA example for encrypting/decrypting messages

examples/rsa.lua

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -67,42 +67,20 @@ local function decrypt(msg)
6767
return bint.upowmod(msg, d, n)
6868
end
6969

70-
-- Converts a buffer of bytes to a big number.
71-
local function text2bn(msg)
72-
local num = bint(0)
73-
local exp = bint(1)
74-
for i=1,#msg do
75-
num = num + string.byte(msg, i) * exp
76-
exp = exp * 256
77-
end
78-
return num
79-
end
80-
81-
-- Converts a big number into a buffer of bytes.
82-
local function bn2text(num)
83-
local bytes = {}
84-
while num > 0 do
85-
local c = string.char((num % 256):tonumber())
86-
table.insert(bytes, c)
87-
num = num // 256
88-
end
89-
return table.concat(bytes)
90-
end
91-
9270
-- Test encrypt and decrypt
9371
print('Message encryption test:')
9472
local msg = 'Hello world!'
9573
print('Message: '..msg)
96-
local x = text2bn(msg, 36)
74+
local x = bint.frombe(msg)
9775
assert(x < n)
9876
print('x = 0x' .. bint.tobase(x, 16))
9977
local c = encrypt(x)
10078
print('c = 0x' .. bint.tobase(c, 16))
101-
assert(c == bint.frombase('33f037cdce6e7da0d7e652ea577b235f8a15ed63060d7e', 16))
79+
assert(c == bint.frombase('81fa941a0bf7a387f0ad060b90a5cd251be4031b4df39a', 16))
10280
local m = decrypt(c)
10381
print('m = 0x' .. bint.tobase(m, 16))
10482
assert(m == x)
105-
local decoded = bn2text(m)
83+
local decoded = bint.tobe(m, true)
10684
print('Decoded: '..decoded)
10785
assert(decoded == msg)
10886
print('success!')

0 commit comments

Comments
 (0)