An openly gay librarian at one of the city’s most prestigious schools was the victim of discrimination when he was suspended for six months for touching students’ backs and whispering in one’s ear, a judge ruled yesterday.

A Department of Education hearing officer had recommended that Christopher Asch be suspended without pay from Stuyvesant HS — while ignoring testimony from a straight female librarian that she behaved in exactly the same way.

“Touching students and whispering in their ear are acceptable practices to maintain order in the library,” said Manhattan Supreme Court Justice Manuel Mendez.

The ruling brings an end to a nightmarish three years for Asch, who was assigned to a “rubber room” after a troubled student who’d made several anti-gay remarks to him complained that Asch had inappropriately touched him.

Asch was arrested, but charges were dropped.

Mendez noted that Asch had been “exposed to the stigma of being described as a ‘pervert’ in the press,” and said he should not be abused by students because he’s gay.

Asch said, “I feel vindicated. There was nothing there to begin with.”