It is not literally illegal to ask, but if they decide not to hire someone after asking the question (or possibly, if they ask some people interviewing for the job, and then decide not to hire someone they didn't ask), it is absurdly easy for the person who wasn't hired to pursue a discrimination claim.
Therefore, most HR departments simply tell you that it's illegal (or prohibited, more precisely). There's a huge amount of legal risk to the company, in asking, and no benefit because it is illegal to actually take the answer into account.
Personally, I would probably answer truthfully in the interview, and then politely tell the recruiter / hiring manager next time I spoke to them, "Thanks, I enjoyed speaking with <person> about the company! By the way, they asked me about my age (or whether I was married, or whatever), and I just wanted to confirm that this information will not be used in a hiring decision. We were making small talk and I didn't mind answering, but I don't think it's relevant to what I can bring to the company." If the recruiter or hiring manager is in the least bit competent, they will immediately panic, and probably end up finding a way for that person to have no role in making your hiring decision, or something.
(This only applies for hiring in the US, if this is in another company things may be totally different)