The Paris Saint-Germain full-back struck 20 minutes from time at Stade Ahmadou Ahidjo after Youssef En-Nesyri cancelled out Gabadinho Mhango's magnificent early effort.
After scraping through Group B in third place, Malawi was making its first appearance in the AFCON knockout stages.
The Flames took a surprise lead in the seventh minute, Mhango catching Yassine Bounou off his line with a wonderful 40-yard lob.
Morocco had only lost one of its previous 11 games when facing an opponent in the competition for the first time.
Vahid Halilhodzic's side equalised in first-half stoppage time as En-Nesyri headed home from Selim Amallah's deep cross.
The contest looked possibly set for extra time until Hakimi emphatically beat Charles Thomu from 30 yards to send his nation through to the last eight, where they will face Ivory Coast or Egypt.