Nadal has struggled with injury and form all year, but he also qualified for the semifinals of the men's singles event earlier in the day.
He and Lopez eventually wore down Romania's Florin Mergea and Horia Tecau, prevailing 6-2 3-6 6-4 in an exhausting final that lasted close to two and a half hours.
It was Nadal's second success at an Olympics, having also won gold in the singles at the 2008 Beijing Games.
The 14-time grand slam winner, who missed the London 2012 through injury, was visibly ecstatic on court Friday when celebrating alongside Lopez.
"It was an amazing experience, especially doing that with one of my best friends, with Marc, it's something unforgettable for me, for both of us, I think," he said.
"Win a gold medal today after two months and a half with no practice, with no preparation at all, just working on the gym, is something that is a dream, no? The moment was unbelievable, and we had fun. We fight hard. The only thing that we can say is that we are very, very happy."
Bronze went to Americans Steve Johnson and Jack Sock, who overcame Canada's Daniel Nestor and Vasek Pospisil in straight sets 6-2 6-4.
Defending Olympics doubles champions Bob and Mike Bryan had pulled out of the Rio Games over fears of the Rio virus.
World No. 5 Nadal had earlier made his way through to the men's singles semifinals with victory over home favorite Thomaz Bellucci.
The 30-year-old is playing his first tournament since a wrist injury ended his bid for a 10th French Open title in June.
He will now face Juan Martin del Potro for a place in Sunday's final after the Argentine player -- who eliminated world No. 1 Novak Djokovic on Sunday
-- beat Spain's Roberto Bautista Agut in straight sets.
Great Britain's Andy Murray overcame 22nd-ranked American Johnson in three sets, and the defending champion will face Japan's Kei Nishikori in Saturday's other semifinal.
Nishikori required two tie-breaks to move past Gael Monfils of France 7-6 4-6 7-6 to set up the tie with the world No. 2.
Puerto Rican joy
In the women's semifinals, Puerto Rico's Monica Puig shocked double Wimbledon champ Petra Kvitova of the Czech Republic 6-4 1-6 6-3.
The 22-year-old has never gone beyond the fourth round of a grand slam, while no Puerto Rican has ever won gold at the Olympics.
Ranked 34th in the world, she will face No. 2 Angelique Kerber of Germany on Saturday.
The Australian Open champion, and losing Wimbledon finalist in July, defeated American Madison Keys 6-3 7-5 in the other semifinal.
Switzerland's top male players Roger Federer and Stan Wawrinka may be missing due to injury, but Martina Hingis and Timea Bacsinszky have a chance to win gold in the women's doubles.
The Swiss duo Czech duo Andrea Hlavackova and Lucie Hradecka 5-7 7-6 (7-3) 6-2 to set up a final clash with Russia's Ekaterina Makarova and Elena Vesnina on Sunday.