In the US, if the cops can convince a judge that they know the evidence is on your device (say, they saw you recording when a murder happened), then they can compel you to testify your knowledge of the crime.
If they want to go looking on your device for information to incriminate you, then that's compelling testimony against yourself, so it's forbidden.
The first case is, of course, subject to lying cops saying, "we saw kiddie porn on his screen when we broke in", which will happen (the way they plant drugs, shoot people and animals and lie about it, etc.). Then it's up to a non-corrupt judge to throw out such evidence based on the cops' lies. But if you're up to something illegal you have to weigh the contempt charge against the danger to yourself of disclosure, and if your password sucks or the judge and cops are corrupt, both.
Frustratingly, the USG claims that the rules for itself don't apply at the border - ostensibly it's operating outside the Law in those scenarios. What could SCOTUS really say about this? - they only judge the Law, not lawlessness.
The case law is different and evolving at the border, but still within the law. The general rule is that search and seizure must be conducted pursuant to a lawful search warrant based upon probable cause.
However, the First Congress, which (more or less) drafted the constitution, also gave customs officers full authority to search ships for contraband without a warrant.
There's a line of cases going back to that which basically means that the sovereign has a right to control what enters the country, and that includes a right to search. There is a little pushback against that today--for example, you need reasonable suspicion in order to do a *destructive* search of a vehicle--but in general border guards are given a great deal of discretion to search you.