Discussion Forum to share and further the development of home control and automation, independent of platforms.

    SmartHome Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Unsolved
    (Last Updated: 8 March 2022)
    • ChatGPT - finally I can now retyre in piece and quite, knowing everting is in goof hands.

      A

      ChatGPT samples:

      Me:

      Tell me about an iot program called openLuup.

      It:

      OpenLuup is an open source home automation system that is built on the VeraLuup platform. It is designed to be easy to install and configure, and provides users with a powerful and versatile way to control their home automation devices. OpenLuup offers a wide range of features, including support for many popular home automation devices, scheduling, scripting, and integration with other services. OpenLuup is designed to be customizable, allowing users to create their own home automation systems. It is an excellent choice for those looking to create their own home automation system without spending a lot of money.

      Me:

      Write an iot program using openLuup.

      It:

      --openLuup IoT Program-- -- Initialize Variables -- local device_id = "MyHomeDevice" local temperature_sensor_id = "MyTemperatureSensor" local temperature_threshold = 75 -- Create Devices -- luup.create_device("OpenLuup Temperature Sensor", 0, device_id, "D_GenericSensor1.xml", "I_GenericSensor1.xml", "S_TemperatureSensor1.xml", "") luup.variable_set("urn:upnp-org:serviceId:TemperatureSensor1", "CurrentTemperature", 0, device_id) -- Start Timer -- luup.call_delay("check_temperature", 10, "", false) --Function to Check Temperature-- function check_temperature() local current_temperature = luup.variable_get(temperature_sensor_id, "CurrentTemperature", 0) --Check Temperature Threshold-- if current_temperature >= temperature_threshold then --Send Alert-- luup.call_action("urn:micasaverde-com:serviceId:HomeAutomationGateway1", "SendTextMessage", {PhoneNumber="1234567890", Message="ALERT! Temperature exceeded threshold!"}, 0) end --Reset Timer-- luup.call_delay("check_temperature", 10, "", false) end

      Me:

      Write an iot program using openLuup.

      It:

      Write an iot program using openLuup. -- openLuup IOT Program -- -- Variables local lampState = false local lampTime = 0 -- Functions function lampTimer() if lampTime > 0 then lampTime = lampTime - 1 if lampTime == 0 then luup.variable_set('urn:upnp-org:serviceId:SwitchPower1', 'Status', 0, lampDeviceID) lampState = false end end end -- Setup luup.call_delay('lampTimer', 60, 0) -- Main Loop while true do -- Check for motion if luup.variable_get('urn:micasaverde-com:serviceId:MotionSensor1', 'Tripped', motionSensorDeviceID) == '1' then if not lampState then luup.variable_set('urn:upnp-org:serviceId:SwitchPower1', 'Status', 1, lampDeviceID) lampState = true -- Set lamp timer to 5 minutes lampTime = 300 end end luup.sleep(1) end

      What??

      luup.sleep(1)

      Not good - looks like I still have some semblance of a job to fulfill.

      Me:

      An iot program called openLuup was written by akbooer. Who is akbooer?

      It: (note: answer redacted and as I understand it, also incorrect re: AltUI):

      akbooer is the pseudonym of the software developer and home automation enthusiast. He is the creator of the openLuup home automation software, which is an open-source version of the Vera home automation system. He is also the creator of the AltUI graphical user interface for openLuup.

      Me:

      Who created of the AltUI graphical user interface for openLuup.

      and

      Me:

      Who created of the AltUI graphical user interface for the home automation system Vera.

      Names two different people - mmmm.

      Regardless very impressive - give it a few more years.

      General Discussion
    • Short survey

      P

      Hi,
      I am a student and recently i am working on smart home project and writing a seminar paper about the way users handle and manage IoT devices. I you have 3 min, please fill below survey. Its really short.
      Thank you in advance, I really appreciate everyone's help.

      General Discussion
    • LibraSun's Dashboard Apps Roundup 2023

      LibraSun

      For what it's worth, I've been putting the finishing touches on a much-updated version of my DP Apps spreadsheet -- specifically intended for HE users, at least for now -- and invite you all to take a gander http://bit.ly/hedb23 at the PDF one-page version.

      Corrections and edits welcome (esp. for the HOMEKIT column, just added yesterday)! Thanks in advance, especially because I'm not a big dashboard user myself, but somehow accepted this role as "keeper of the list" as it were.

      General Discussion
    • Separate switching bulb in one ceiling light

      P

      Hello guys,

      I would like to achieve two different things with lights, but I am not sure it could be done. I am starting with smart things, and I am far from any electrician knowledge, wo any help is really appreciated.

      I have dumb switches in my hall, controlled from 3 places. I understood that installing one smart module before first switch will make them "hybrid", both smart controlled and dumb controlled.

      I would like to buy ceiling light with two bulb sockets. What I would like to achieve is I would like to have one bulb for normal daily usage (lets say cold white full brightness), and second for night time (aprox from 10pm till morning) with some red/orange - minimum brightness.

      So question are:

      Is there a way to keep both bulbs turning-on separated? So only one will be on during day, and then only second during night?

      And could that be done with pressing dumb switch? What would I need to achieve it? (maybe another module into the ceiling lights)

      Thank you in advance

      General Discussion
    • How to reset kwh

      B

      Aften some testing I watt to clear KWH how ?

      Regards Bjarne

      General Discussion
    • Need help in finding the right smart switch for my kitchen lights

      M

      Hello,
      I have a kitchen light that can be controlled by two switches, using either to turn it off or on. I have been slowly changing things over to be a smart home but this is the first switch I am attempting to install.
      I am in a double wide modular home (mobile) that was built in 1994.
      At first I thought I would need a 3 way switch but when taking the normal switches apart I realized that was incorrect because the wiring on my switches are different than anything I could find online.
      For one a 3 way smart switch requires 5 wires and there are only 2 wires going into the primary switch with 3 wires going into the secondary switch from the primary switch (at least I think the 3 wires connect the two switches together). Images will be attached of the wiring.
      There are two wires (one black and one white) going into the first switch and 3 wires (black, white, and red) going out of that and into the second switch (I assume). The odd thing is the red wire going to the second switch is connected to the white wire going into the first switch and the white wire going into the second switch seems to be a bridge wire or a traveler wire. Not exactly sure. You will see what I mean in the images.
      I need to know what kind of smart switch I can use in this set up with one remaining a normal switch.
      Note that for some reason the images got switched around when uploading them. The image with 2 wires on one side and 3 on the other is what I think is the primary and the image with just 3 wires is the secondary.
      Primary.jpg Secondary.jpg

      General Discussion
    • OT: Universal Remote

      CatmanV2

      You lot are more likely to have a view than most I know. Our much used Logitech Harmony is (not so) slowly dying.

      And Logitech have discontinued the entire line.

      And no one else appears to be making something similar.

      Was going for a Sofabaton X1, but no numeric keypad. Sofabaton U1, but no favourites.

      Anyone got suggestions?
      Needs to have those features, oh and not be only a phone app.....

      C

      General Discussion
    • The Home Automation Controller Pyramid

      rafale77

      Since one member asked at one point about the "front end" and "back end", I drew this showing the controller from the base to the tip along with what I have found to be the best options from my testing. Almost every controller will try to integrate all elements, especially commercial ones but... they all have strengths and weaknesses so if one can have a medley of the best ones...

      Screen Shot 2020-05-14 at 07.11.06.png

      General Discussion
    • Thread removed - why?

      Black Cat

      I was just going to add my support for a Update Button for the bare bones version of MSR and find the thread has been removed.
      I'm wondering what was so provocative that required it's removal?
      Have we become as paranoid as an owner of another forum?

      Anyway +1 for an Update Button.

      General Discussion
    • 3-way smart switches in separate buildings.

      D

      So, I think I'm in a bit of an unusual situation. I work at a camp & retreat center that has wifi throughout. I want to put a few switches in the office that can control outdoor lighting throughout the camp. We currently have switches in each of the buildings, but it is a particularly frustrating job to get all the lights on in the evening when it is brutally cold out or we are short staffed.

      Most of our staff is not very tech savvy (my boss literally has his wife print out his emails for him each day!!!) so, I'd love to avoid having to set up any sort of raspberry pi or new phone app.

      Is there type of 3-way switch that can connect to the wifi, turn on a light in another building AND turn on an indicator light in the office, without having any sort of wire running between the buildings? Hopefully looking for a simple solution without breaking the bank too.

      I greatly appreciate any input that you can give. Thank you!

      General Discussion
    For those who registered but didn't received the confirmation email, please send an email to support@smarthome.community with the email you used

    Unsolved Lua - Code to encrypt / decrypt with AES 128 CBC

    General Discussion
    3
    27
    950
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • parkerc
      parkerc last edited by parkerc

      Hi

      I’m looking to rework some code I found online so I can use it on Vera, and while I’ve managed to translate / convert a number of things, I’ve got stuck on a few things it does, around encryption/decryption etc.

      All the original Lua code is here - > (https://forum.logicmachine.net/showthread.php?tid=232&pid=16580#pid16580 )

      Plus there looks to be a python version too here - > (https://github.com/florianholzapfel/panasonic-viera/issues/9#issuecomment-476919658)

      Here’s an extract of the code where AES 128 CBC is required?

      function encrypt_soap_payload(data, key, hmac_key, iv)
      payload = '000000000000'
        n = #data
      
      payload = payload .. string.char(bit.band(bit.rshift(n, 24), 0xFF))
      payload = payload .. string.char(bit.band(bit.rshift(n, 16), 0xFF))
      payload = payload .. string.char(bit.band(bit.rshift(n, 8), 0xFF))
      payload = payload .. string.char(bit.band(n, 0xFF))
      
      payload = payload .. data
      
       aes_cbc, err = aes:new(key, nil, aes.cipher(128, 'cbc'), { iv = iv }, nil, 1) 
        ciphertext = aes_cbc:encrypt(payload)
        sig = encdec.hmacsha256(ciphertext, hmac_key, true)
        encrypted_payload = encdec.base64enc(ciphertext .. sig)
        return encrypted_payload
      end
      
      function decrypt_soap_payload(data, key, hmac_key, iv)
        aes_cbc, err = aes:new(key, nil, aes.cipher(128, 'cbc'), { iv = iv }, nil, 0) 
        decrypted = aes_cbc:decrypt(encdec.base64dec(data))
        decrypted = string.gsub(string.sub(lmcore.strtohex(decrypted), 33), '%x%x', function(value) return string.char(tonumber(value, 16)) end) 
        return decrypted
      end
      

      I can get to the point where I can create the parameters for the payload encrypt request (example below), it’s just the encryption/decryption I cant do..

      data="1234"
      key="\\S„ßÍ}/Ìa5!"
      hmac_key="¹jz¹2¸F\r}òcžÎ„ 臧.ª˜¹=¤µæŸ"
      iv=" {¬£áæ‚2žâ3ÐÞË€ú "
      

      I’ve found this aes.lua (https://github.com/openresty/lua-resty-string/blob/master/lib/resty/aes.lua ) module online, but that requires loads of others modules too, most notably ffi.lua. Which I’d ideally like to avoid.

      I also came across this aes128.lua (https://github.com/somesocks/lua-lockbox/blob/master/lockbox/cipher/aes128.lua ) but i’m not sure how that handles all the other parameters e.g specify the cbc aspect etc.

      Finally there’s this aes256ecb.lua script (https://github.com/idiomic/Lua_AES/blob/master/AES.lua) , could that be converted to aes 128 cbc and then used in the above?

      Any help/advice on this would be appreciated..

      1 Reply Last reply Reply Quote 0
      • parkerc
        parkerc last edited by

        I can see on Vera, that it has openssl installed, is that an option ?

        root@MiOS_ 12345678:~# openssl version
        OpenSSL 1.0.2l  25 May 2017
        
        root@MiOS_ 12345678:~# openssl ciphers
        ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:SRP-DSS-AES-256-CBC-SHA:SRP-RSA-AES-256-CBC-SHA:SRP-AES-256-CBC-SHA:DH-DSS-AES256-GCM-SHA384:DHE-DSS-AES256-GCM-SHA384:DH-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:DH-RSA-AES256-SHA256:DH-DSS-AES256-SHA256:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:DH-RSA-AES256-SHA:DH-DSS-AES256-SHA:ECDH-RSA-AES256-GCM-SHA384:ECDH-ECDSA-AES256-GCM-SHA384:ECDH-RSA-AES256-SHA384:ECDH-ECDSA-AES256-SHA384:ECDH-RSA-AES256-SHA:ECDH-ECDSA-AES256-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:PSK-AES256-CBC-SHA:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:SRP-DSS-AES-128-CBC-SHA:SRP-RSA-AES-128-CBC-SHA:SRP-AES-128-CBC-SHA:DH-DSS-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:DH-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:DHE-DSS-AES128-SHA256:DH-RSA-AES128-SHA256:DH-DSS-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:DH-RSA-AES128-SHA:DH-DSS-AES128-SHA:DHE-RSA-SEED-SHA:DHE-DSS-SEED-SHA:DH-RSA-SEED-SHA:DH-DSS-SEED-SHA:ECDH-RSA-AES128-GCM-SHA256:ECDH-ECDSA-AES128-GCM-SHA256:ECDH-RSA-AES128-SHA256:ECDH-ECDSA-AES128-SHA256:ECDH-RSA-AES128-SHA:ECDH-ECDSA-AES128-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:SEED-SHA:PSK-AES128-CBC-SHA:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:ECDH-RSA-RC4-SHA:ECDH-ECDSA-RC4-SHA:RC4-SHA:RC4-MD5:PSK-RC4-SHA:ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:SRP-DSS-3DES-EDE-CBC-SHA:SRP-RSA-3DES-EDE-CBC-SHA:SRP-3DES-EDE-CBC-SHA:EDH-RSA-DES-CBC3-SHA:EDH-DSS-DES-CBC3-SHA:DH-RSA-DES-CBC3-SHA:DH-DSS-DES-CBC3-SHA:ECDH-RSA-DES-CBC3-SHA:ECDH-ECDSA-DES-CBC3-SHA:DES-CBC3-SHA:PSK-3DES-EDE-CBC-SHA
        

        There seems a number of related posts online - where similar attempts have been made e.g. https://stackoverflow.com/questions/65918428/how-to-provide-string-iv-and-key-to-openssl-decrypt-command

        Never having done anything like this before, looking for some support/guidance from anyone who understands all this cipher/encryption stuff much more than I 🙂

        1 Reply Last reply Reply Quote 0
        • toggledbits
          toggledbits last edited by

          Absolutely OpenSSL is the way to go, rather than trying to implement the encryption in Lua. You can use os.execute() or io.popen() to run the command and capture the output. You're probably looking at some variant of:

              openssl aes-128-cbc -e -a -K hex-key -iv hex-iv [-in xxx]
          

          Author of Multi-system Reactor and Reactor, DelayLight, Switchboard, and about a dozen other plugins that run on Vera and openLuup.

          1 Reply Last reply Reply Quote 0
          • parkerc
            parkerc last edited by

            Thanks @toggledbits

            I’ve been playing around with OpenSSL a little this morning, I’ve, not had much success so far., based on the source code, it looks like i need to encrypt the generated payload with the created key and iv using aes 128 cbc.. Does that sound right to you.. (Looking at OpenSSL guide, it seems pretty comprehensive and complex.- https://www.openssl.org/docs/man1.1.1/man1/openssl-enc.html 😞 )

            Here’s my code so far, any thoughts/suggestions welcome..

            local name = "openssl"
            local version = "version"
            local data="1234"
            local key="\\S„ßÍ}/Ìa4!"
            local hmac_key="¹jz¹2¸F\r}òcžÎ„ 臧.ª˜¹=¤µæŸ"
            local iv=" {¬£áæ‚2žâ3ÐÞË€ú "
            local payload = "0000000000001234"
            
            --local buildsslcommand1 = name .." "..version
            --local buildsslcommand2 = "openssl aes-128-cbc -e -a -K hex-"..key.." -iv hex-"..iv.."[-in xxx]"
            --local buildsslcommand3 = "openssl enc -aes-128-cbc -iv "..iv.." -k "..key.." | hexdump -C"
            local buildsslcommand = "openssl enc -aes-128-cbc -nosalt -e -a -A "..payload.." -K "..key.." -iv "..iv
            print("Command to send = " ..buildsslcommand)
            
            local file = assert(io.popen(buildsslcommand, 'r'))
            local output = file:read('*all')
            file:close()
            print(string.len(output)) --> just count what's returned.
            print(output) -- > Prints the output of the command.
            
            1 Reply Last reply Reply Quote 0
            • toggledbits
              toggledbits last edited by

              Practice on the command line and don't worry about the Lua until you know how the command works and what you need to give it.

              Your key and IV have to be hex, so that's your first challenge. The command will want to read stdin if you don't specify -in <file>; you can't put the payload on the command line directly. Plus it contains binary data, so that's a non-starter. So at a minimum you're going to be writing the payload to a temporary file and encrypting that with -in. OpenSSL can write the encrypted output to stdout (it will if you don't specify -out <file>), which is good because you can read that directly when using io.popen(), so that part's going to be OK.

              Author of Multi-system Reactor and Reactor, DelayLight, Switchboard, and about a dozen other plugins that run on Vera and openLuup.

              1 Reply Last reply Reply Quote 0
              • parkerc
                parkerc last edited by parkerc

                Thanks @toggledbits ,

                To make the key and iv hex, could I use binascii.lua (https://github.com/tst2005/binascii/blob/master/binascii.lua) ?

                —Converts a string of bytes to a hexadecimal string
                local function hexlify(s)
                	local a = {}
                	for i=1,#s do
                		local c = s:sub(i,i)
                		local byte = c:byte()
                		a[#a+1] = ('%02X'):format(byte)
                	end
                	return table.concat(a)
                end
                

                As for the OpenSSL command line structure, I’ve come across a number of different examples online - this one seems to relate to what you’re suggesting (I’d just need to change it to 128, rather than 256)

                openssl enc -aes-256-cbc -nosalt -e -a -A -in input.dat -K '7c07f68ea8494b2f8b9fea297119350d78708afa69c1c76' -iv 'FEDCBA987654321' -out input-test.enc
                

                QQ : You mentioned that I’m going to need to write the payload to a temp file and encrypt it with -in?

                How does -in do any encryption?

                In the OpenSSL manual it just says the following about -in and -out

                -in filename
                The input filename, standard input by default.
                
                -out filename
                The output filename, standard output by default.
                
                toggledbits 1 Reply Last reply Reply Quote 0
                • toggledbits
                  toggledbits @parkerc last edited by

                  @parkerc said in Lua - Code to encrypt / decrypt with AES 128 CBC:

                  QQ : You mentioned that I’m going to need to write the payload to a temp file and encrypt it with -in?

                  You need to use -in on the encryption command to tell it to read from a file. You didn't have -in in your previous example, you just put the payload on the command line, and that doesn't work.

                  The hex conversion doesn't need two steps for the byte conversion and math for target array position:

                  -- Converts a string of bytes to a hexadecimal string
                  local function hexlify(s)
                  	local a = {}
                  	for i=1,#s do
                  		a[i] = ('%02X'):format( s:byte( i ) )
                  	end
                  	return table.concat(a)
                  end
                  

                  Author of Multi-system Reactor and Reactor, DelayLight, Switchboard, and about a dozen other plugins that run on Vera and openLuup.

                  1 Reply Last reply Reply Quote 0
                  • parkerc
                    parkerc last edited by parkerc

                    Ok, not sure how far I’ve progressed with this, but hopefully I’m getting somewhere ??

                    Here are the values created earlier..

                    local key= "\\S„ßÍ}/Ìa4!"
                    local iv = "{¬£áæ‚2žâ3ÐÞË€ú"
                    local payload = "0000000000001234"
                    

                    I’ve put the payload value into a file..

                    local file = "etc/payload.txt"
                    local outf = io.open(file, "w")
                    outf:write(payload)		
                    outf:close()
                    

                    Then created Hex values of the key and iv

                    local function hexlify(s)
                    	local a = {}
                    	for i=1,#s do
                    		a[i] = ('%02X'):format( s:byte( i ) )
                    	end
                    	return table.concat(a)
                    end
                    
                    print(hexlify(key))
                    print(hexlify(iv))
                    

                    keyHEX = "5C53E2809EC39FC38D7D191E2FC38C1D61057F3421"
                    ivHEX = "7BC2ACC2A3C3A1C3A6E2809A32C5BEC3A233C390C39EC38BE282ACC3BA"

                    Then I’ve taken those new hex values and accessed the command line of vera to run the following openssl command I created…

                    openssl enc -aes-128-cbc -nosalt -e -a -A -in etc/payload.txt -K '5C53E2809EC39FC38D7D191E2FC38C1D61057F3421' -iv '7BC2ACC2A3C3A1C3A6E2809A32C5BEC3A233C390C39EC38BE282ACC3BA' -out etc/payload2.txt
                    

                    The above resulted in etc/payload2.txt being created, however it's empty and the command line returns the following messages.

                    hex string is too long
                    invalid hex iv value

                    Other than checking how the initial key and I’ve values are created again, is there anything else I need to look into/check ?

                    1 Reply Last reply Reply Quote 0
                    • toggledbits
                      toggledbits last edited by toggledbits

                      Those initial values for key and IV being binary data in strings could be a problem. Your editor may be wrecking them because it thinks they are Unicode, or they've already been wrecked along the way by other means. Both are supposed to be 16 bytes, and you've got 29 for IV and 21 for the key, so something has definitely gone wrong, and Unicode/UTF-8 encoding and decoding in the file handling is a prime suspect.

                      Fortunately, the IV doesn't really matter, I think. You could just use the first 16 bytes of the payload for testing. But it's supposed to be a 16-byte (128 bit) nonce, used only one time with the key (so if you encrypt something else with the same key, you should use a different IV). Maybe just generate 16 random bytes and call it good, but make sure to seed the random number generator, otherwise it generates the same 16 "random" numbers after every restart (that's a feature, actually, but you have to remember to seed in production to get away from it).

                      And really, probably the key doesn't matter either. You need both the key and IV to encrypt and decrypt, so it's not like you are dealing with a known key from another system like a remote API (unless they are doing this all wrong and using the same key and IV for every payload--that would be an... error). Pick 16 bytes and go to town!

                      patrick@drupal:/tmp$ echo "I am a secret message." > in.txt
                      patrick@drupal:/tmp$ cat in.txt
                      I am a secret message.
                      
                      # Encrypt
                      patrick@drupal:/tmp$ openssl aes-128-cbc -e -a -in in.txt -K '9988227744aaff003388ffccee1188ff' -iv '112233445566778899aabbccddeeff00' -out out.txt
                      patrick@drupal:/tmp$ cat out.txt
                      MQi9QVm1/R3dvZncbX0nQeRqlf0+2oFcMuW/vp0FQ2Q=
                      
                      # Now decrypt
                      patrick@drupal:/tmp$ openssl aes-128-cbc -d -a -in out.txt -K '9988227744aaff003388ffccee1188ff' -iv '112233445566778899aabbccddeeff00'
                      I am a secret message.
                      

                      Author of Multi-system Reactor and Reactor, DelayLight, Switchboard, and about a dozen other plugins that run on Vera and openLuup.

                      1 Reply Last reply Reply Quote 0
                      • parkerc
                        parkerc last edited by parkerc

                        Thanks @toggledbits

                        I think you’re right about the Lua/Luup editor wrecking the format of the values being generated, plus I’m perhaps not helping matters by working on various parts of the overall code separately ; so I have been copying things over.

                        FYI - You can see how the generated values are stored/presented differently (one image is via a print screen using LuaView and the other is writing them as new variables into Vera)

                        ABC0EDD2-A9CA-4890-9D49-2DB56D420BBC.jpeg

                        483FE064-8895-4BB1-8DC3-78967047FB5D.jpeg

                        I’m going to try and do as much as I can using the Vera written values, as ultimately that’s where my target for where this code will need to eventually run..

                        1 Reply Last reply Reply Quote 0
                        • toggledbits
                          toggledbits last edited by

                          OK, yeah, so big problem, you cannot store binary data in state variables. That is going to fail, 100%. State variables are character strings, and assumed to contain character data, and when they are stored, they are put through UTF-8 encoding and decoding. Your binary data is going to look like Unicode characters to the innards of Luup throwing this stuff around, and anything that isn't a valid codepoint is going to get changed to something else (and boom, data corrupted), while converting it to JSON to store on flash and back, etc.

                          Store everything in hex or base64.

                          Author of Multi-system Reactor and Reactor, DelayLight, Switchboard, and about a dozen other plugins that run on Vera and openLuup.

                          1 Reply Last reply Reply Quote 0
                          • parkerc
                            parkerc last edited by parkerc

                            What would I do without you 🙂

                            Ok, so I can still write to a device variable in Vera, I’d just need to encode it first , in either one of those two options. e.g like this if base64?

                            
                            local function base64_encode(data)
                            	local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
                                return ((data:gsub('.', function(x) 
                                    local r,b='',x:byte()
                                    for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
                                    return r;
                                end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
                                    if (#x < 6) then return '' end
                                    local c=0
                                    for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
                                    return b:sub(c+1,c+1)
                                end)..({ '', '==', '=' })[#data%3+1])
                            end
                            
                            local key = string.char(unpack(key_vals)) - - 
                            local keyEnc = base64_encode(key)
                            luup.variable_set("urn:nodecentral-net:serviceId:NodeCentral1","key",keyEnc, 1187)
                            
                            1 Reply Last reply Reply Quote 0
                            • toggledbits
                              toggledbits last edited by

                              It's easier than that in Luup...

                              local mime = require("mime")
                              local encoded = mime.b64( "Hello world!" );
                              local decoded = mime.unb64( encoded );
                              luup.log( decoded, 2 )
                              

                              Author of Multi-system Reactor and Reactor, DelayLight, Switchboard, and about a dozen other plugins that run on Vera and openLuup.

                              1 Reply Last reply Reply Quote 0
                              • parkerc
                                parkerc last edited by

                                Awesome, thanks - I often forget what’s already there in luup.. !

                                Also am I right in saying that i only need to enc/dec in hex or base64 if I’m planning to store (read/write) those values/variables, if I can keep them ‘active; and flowing within the code itself (in memory) then, I’m ok ?

                                1 Reply Last reply Reply Quote 0
                                • toggledbits
                                  toggledbits last edited by

                                  Yes, in memory is fine. So for example, you may generate IV from random numbers byte by byte, put it through b64 or hex before storing it on a state variable. For openssl, you'll be giving key and IV in hex, so that seems a sensible way to keep it. Once it's converted to hex, you'll never need to reverse that, since it can be stored in a state variable as hex, and can be handed directly to openssl as hex.

                                  Author of Multi-system Reactor and Reactor, DelayLight, Switchboard, and about a dozen other plugins that run on Vera and openLuup.

                                  1 Reply Last reply Reply Quote 0
                                  • parkerc
                                    parkerc last edited by

                                    This time round, I seem to have generated some new hex values this time, which I’ve used in a io.popen openssl command, feels a bit better, but sadly not quite yet right (yet).. FYI

                                    openssl enc -aes-128-cbc -nosalt -e -a -A -in etc/payload.txt -K 'enNIQi9wNmYxd1RDUXMvNHJhdHNGZz09' -iv 'B6B1919A88C696AE87A692B1BBADCE9B' -out etc/payload2.txt
                                    non-hex digit
                                    invalid hex key value
                                    
                                    1 Reply Last reply Reply Quote 0
                                    • toggledbits
                                      toggledbits last edited by

                                      Well the key you show is definitely not hex, because 16 bytes of hex should be 32 characters long with only 0-9, A-F. Looks like you have base64 for the key, not hex.

                                      Author of Multi-system Reactor and Reactor, DelayLight, Switchboard, and about a dozen other plugins that run on Vera and openLuup.

                                      1 Reply Last reply Reply Quote 0
                                      • parkerc
                                        parkerc last edited by parkerc

                                        Progress at last ! well I’ve at least got the key and iv in the correct hex format for the OpenSSL aes cbc encryption command to work.🥳

                                        Which leads me on to the next part, where the output of the above is referred to as the ciphertext;, of which I now need to do the following with..

                                          ciphertext = MyopensslAEScbcCall()
                                          sig = encdec.hmacsha256(ciphertext, hmac_key, true)
                                          encrypted_payload = encdec.base64enc(ciphertext .. sig)
                                          return encrypted_payload
                                        

                                        hmacsha256 seems to be next, and it might also be something I could do with OpenSSL too ? -> https://unix.stackexchange.com/questions/610039/how-to-do-hmacsha256-using-openssl-from-terminal ?

                                        I also found this too - https://github.com/jqqqi/Lua-HMAC-SHA256/blob/master/sha256.lua

                                        @toggledbits any suggestions/recommendations on what to do with this next part ?

                                        1 Reply Last reply Reply Quote 0
                                        • toggledbits
                                          toggledbits last edited by toggledbits

                                          I would stick with OpenSSL. You just need to assemble the correct bits (HMAC key and ciphertext) to send to the hash function, compute the hash, then append the hash to the ciphertext. The trick here will be that you currently have the AES encyption outputting its result base64-encoded... you can't append the signature to that. You need the ciphertext output in binary for that, so you need to remove the -a (and -A) to let the output be binary. Then you can put that into the hash. And then you can take the (binary) hash output and append that to the binary ciphertext, and then you base64 encode the assembled result at the very end. The whole thing takes a few steps. I would recommend writing a shell script to do all the steps, and just have Lua run the shell script. You can then more easily develop and test the steps (because they are all in the shell script and runnable from the command line).

                                          Author of Multi-system Reactor and Reactor, DelayLight, Switchboard, and about a dozen other plugins that run on Vera and openLuup.

                                          parkerc 1 Reply Last reply Reply Quote 0
                                          • parkerc
                                            parkerc last edited by

                                            Thanks @toggledbits - I struggle enough with Lua, so i admire your optimism in thinking I could create a shell script too 🙂

                                            I must admit, I can’t help but feel like I’m making this more complicated that it needs to be, especially as there are working Lua and Python scripts already out there, which seem to be doing everything natively (although I do admit much of this thread is trying to plug holes in Vera 😞 )

                                            With that said, the following might help you understand the bigger picture of what I’m trying to replicate, and maybe help me more, as I found some related posts, the first one which uses python e.g. https://github.com/florianholzapfel/panasonic-viera/issues/9 - and I’ve extracted the related HMAC part below.

                                            …
                                            # Let's encrypt it with AES-CBC! We need to make sure we pad it to a multiple of 16 bytes beforehand
                                            aes = AES.new(key, AES.MODE_CBC, iv)
                                            ciphertext = aes.encrypt(pad(payload))
                                            
                                            # Calculate the HMAC-SHA-256 signature of our encrypted payload
                                            sig = hmac.new(hmac_key, ciphertext, hashlib.sha256).digest()
                                            
                                            # Concatenate the HMAC signature to the encrypted payload and base64 encode it, and we're done!
                                            encrypted_payload = base64.b64encode(ciphertext + sig)
                                            

                                            Plus there’s this pure Lua version called Haslib -> https://github.com/howmanysmall/Rewrites/blob/master/src/HashLib.lua - which looks like it might be promising to add to Vera as a module ?

                                            USAGE:
                                            	Input data should be a string
                                            	Result (SHA digest) is returned in hexadecimal representation as a string of lowercase hex digits.
                                            
                                            	Simplest usage example:
                                            		local HashLib = require(script.HashLib)
                                            		local your_hash = HashLib.sha256("your string")
                                            

                                            Looking at the functions within the latter HashLib.lua file, it has one called local function hmac(hash_func, key, message) which makes me wonder could i use that and do the following.. ?

                                            local HashLib = require(script.HashLib)
                                            local mySig = HashLib.hmac(sha256, ciphertext, hmac_key) 
                                            
                                            1 Reply Last reply Reply Quote 0
                                            • First post
                                              Last post

                                            Welcome. If you’d like to participate in the discussion, rather than just read, then you can join the forum. As a member, you can interact with others here to share your experience and ask the questions you need answered.

                                            Powered by NodeBB | Contributors
                                            Hosted freely by PointPub Media Communications Inc. | Contact us