It puts Barcelona level on points with Real Madrid, but with a better goal difference and head-to-head record.
Casemiro had put the hosts ahead before Messi and Ivan Rakitic goals put Barcelona in front and Sergio Ramos was shown a red card.
Substitute James Rodriguez thought he had earned Madrid a point late on.
But Messi, who scored his first with a superb jinking run and finish, fired in from the edge of the area to win it for Barcelona.
Both Messi and Cristiano Ronaldo had earlier missed good opportunities to give their sides the lead, with the Argentina international poking wide of an open goal before the break and Ronaldo slicing over in the second half.
Madrid – who have a game in hand on Barcelona – also felt they should have had a penalty when Ronaldo was clipped by Samuel Umtiti after only two minutes.