As others have said, even when they are legally in the wrong border security agents can still ruin your day or your entire trip—they can easily make you miss your domestic connecting flight. They can also keep your equipment for years—as they are doing in this very case. The simplest strategy is to not have any kind of valuable data on your electronic devices when you cross the border. You can send all of your data via the internet. Don't carry it on your person where you have to suffer harassment to protect it.
Your devices should look completely normal while containing no personal information about you. You should be able to hand them over to a border security agent and give a working password that has no relation to your usual one. When they log in, they should see a device with no personal information of any kind. No photos, no incoming text messages, no emails, no documents, no web browser history, etc.
A few people have suggested a dummy password that logs into a restricted access dummy account. That's risky. If they take your phone or laptop into another room for an hour they may discover that it has inaccessible data on it and the usual harassment will ensue. Setting your phone to wipe itself after three failed password attempts may work, but only if they can log in with the correct password after it’s been wiped and see what looks like a normal, working phone.
You have to do it every time, but wiping and preparing your devices before crossing the border is the most effective solution.
On a side note, my phone is a bit of a problem. So long as the SIM is in it, it will receive any incoming calls or text messages. I can wipe those just before I go through customs, but the agents can read anything that comes in while they have the phone. I could hide the SIM somewhere in my luggage, but then I'd have a suspicious phone and they might find the SIM and get angry. I guess the best strategy is to leave your SIM at home and buy a temporary phone plan and SIM at your destination.