The unexpected result denied Brazil what would have been the first Olympic soccer championship for a country that has won everything else in the sport.
It was the third silver medal at the Olympics to go with two bronze ones for Brazil. A gold finally seemed likely this year, especially after Spain was eliminated before the knockout round began.
It was a massive win for Mexico, a nation that shares passion for the game with Brazil but has always had to live in the Brazilians' shadow on the international stage.
Javier Aquino stole the ball deep in Brazil's territory in the opening moments of the contest and quickly sent it to Peralta, who had darted in alone into the left side of the penalty area.
Peralta made no mistake, firing the shot between goalkeeper Gabriel Vasconcelos Ferreira and the left post. It was only the second time a goal had been scored in the opening minute of an Olympic gold medal game.
The Brazilians never recovered and a pesky, physical Mexican defense protected the narrow lead until Peralta struck again in the 75th minute.
A free kick taken from the right side by Marco Fabian sailed into the penalty area and the set play worked to perfection. Peralta ran around a screen while the ball was in the air and was all alone when it arrived. His strong header was rifled into the net for what turned out to be the game-winner.
Givanildo Vieira de Sousa, who in the soccer world is known simply as Hulk, scored in stoppage time for Brazil.
Mexico's best previous showing in an Olympic soccer tournament came when that country hosted the 1968 Games. The Mexicans lost in the semifinals that year and then fell in the bronze medal match as well to Japan 2-0.
The bronze medal in London was decided on Friday when South Korea defeated Japan in the third-place game.