The US and Canada both extend an expectation of privacy to public restrooms. Police officers in the US, for example, cannot peek into a bathroom stall to see if you’re doing anything illegal (due to both the Fourth and Fourteenth Amendments).* Strictly speaking, then, it is perfectly legal to masturbate in a public restroom in either country.
What makes it complicated, however, is the circumstances of getting caught. As already noted, you can’t be prosecuted if someone peeks in on you. In fact, you could technically prosecute them for invading your privacy. But it’s unlikely that would ever work out in your favor because all the peeper has to do is claim that you made a noise that caught their interest.
That would get you in trouble because your expectation of privacy only applies so long as you’re keeping to yourself. As soon as you make what you’re doing known to anyone else, it counts as public lewdness. This doesn’t matter with ordinary bathroom noises because they aren’t considered lewd under the law. But if you do anything to make a “lewd” act public, then what you are doing is no longer considered legal.**
——————————
* There’s a surprising amount of US case law on this issue, by which I mean both restroom privacy in general and restroom masturbation.
** Note that the above answer only applies to the situation described in the OP. If the restroom is not designed in such a way as to give privacy in the first place—e.g., if the stalls lack doors or the doors do not close properly—then no expectation of privacy exists.