Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- link is a secure device-pairing system that can be used in a multitude of ways
- ]]--
- local links
- local function genNew()
- local t = ""
- for i= 1, 15 do
- t = t .. string.char( math.random( 0, 255 ) )
- end
- return t
- end
- local function increment( secret, current )
- local new = ""
- for i = 1, 15 do
- local n = tostring( secret:sub( i, i ):byte()^math.min( current:sub( i, i ):byte(), 128 ) )
- print( n )
- if #n < 5 then
- new = new .. string.char( tonumber( n:sub( 1, 2 ) ) )
- else
- local result = math.floor( tonumber( n:sub( 1, 2 ) ) / 99/math.ceil( #n - 2 ) )
- new = new .. n:sub( result * 2 + 1, result * 2 + 2 )
- end
- end
- return new
- end
- local function save() --saves the links
- local file = fs.open( ".links", "w" )
- file.write( textutils.serialize( links ) )
- file.close()
- end
- --loading linkages
- do
- local file = fs.open( ".links", "r" )
- if file then
- local data = file.readAll()
- file.close()
- links = textutils.unserialize( data )
- else
- links = {}
- links.__secret = ""
- for i = 1, 15 do --generate a secret key
- links.__secret = links.__secret .. string.char( math.random( 31, 127 ) )
- end
- save()
- end
- end
- function addLink( devicename, secret )
- links[ devicename ] = {secret = secret, current=genNew()}
- end
- function getSecret()
- return links.__secret
- end
- function setDeviceName( name )
- links.__deviceName = name
- end
- local mt = {
- send = function( self, message )
- local auth = increment( links[ self.deviceName ].secret, links[ self.deviceName ].current )
- rednet.broadcast( textutils.serialize( {msg=message, auth=auth} ) )
- local id = os.startTimer( 0.05 )
- while true do
- local event = {os.pullEvent()}
- if event[ 1 ] == "rednet_message" and event[ 2 ] == "_confirm_" then
- links[ self.deviceName ].current = auth
- save()
- break
- elseif event[ 1 ] == "timer" and event[ 2 ] == id then
- break
- end
- end
- end,
- event = function( self, tEventData )
- local e = tEventData or {os.pullEvent()}
- if e[ 1 ] == "rednet_message" then
- local msg = textutils.unserialize( e[ 3 ] )
- local new = increment( links.__secret, links[ self.deviceName ].current )
- if type( msg ) == "table" and msg.auth == new then
- links[ self.deviceName ].current = new
- save()
- rednet.send( e[2], "_confirm_" )
- return "link_message", self.deviceName, msg
- end
- end
- return e
- end,
- }
- function establishLink( deviceName )
- return setmetatable( {deviceName = deviceName}, {__index = mt} )
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement