As judges like to say, ignorance of the law is no defense to criminal charges. There are exceptions, but the overwhelming majority of crimes don’t require that the defendant know that his or her conduct is illegal.
People charged with crimes often argue that they were mistaken not as to the law, but as to the facts. Factual mistake is more likely to provide a viable defense than legal mistake. But not all crimes lend themselves to a mistake-of-fact defense. For example, those charged with statutory rape commonly assert that they didn’t know their partner wasn’t old enough to consent. In this situation, the defendant isn’t arguing mistake of law (that he didn’t know having sex with a minor was illegal), but rather, mistake of fact (that he didn’t know how old his sexual partner was). Mistake of fact is often a viable defense to criminal charges, but in most states it’s not when statutory rape is involved.
For more on state of mind in criminal cases, including an example of ignorance of law as a valid defense, see How Defendants' Mental States Affect Their Responsibility for a Crime.