IANAL, but as a green card holder my lawyer told me they cannot deny you entry without an order from an immigration judge (likely if travel was not brief - more than 180 days, or they engaged in illegal activity after leaving the United States as defined in 8 U.S.C. 1101(a)(13)) - you only have to answer questions about your name and status, nothing more - though, obviously it will likely cause delays.
It's similar in Canada; permanent residents and citizens have the legal right to reentry and it can't be denied. But that right applies to you, not anything you are carrying. Play that game and you'll probably lose the device to border security.
Losing the device in such circumstances is definitively the best outcome. There is a shit ton of data that these devices have and the law is so complex that you probably committed a crime somewhere without you realizing it.
Yikes, I don't know about border detentions. The right to representation attaches (generally) at the start of criminal proceedings, pursuant to the 6th Amend. Is a border detention a criminal proceeding? Probably it's just some sort of administrative function and so your rights are certainly much slimmer at this point.
Still, give them the code if you want.