I think the reason it's illegal for prisoners to masturbate is because of the female prison guards.
The prison guards get offended by the males masturbating in their prison cells when they make their rounds and look into the prison cells and see a prisoner masturbating.