The two men smuggled themselves into a ferry in Tangier bound for the southern Spanish port of Algeciras in early October by clinging to the undercarriage of a freight truck that boarded the boat, police said in a statement.
As soon as they arrived in Algeciras they were approached by two other Moroccan men who lured them to an apartment in the city with the promise of food and the chance to take a bath after the trip.
The migrants were tied up and beaten and their family members received threatening phone calls demanding €4,000-5,000 ($4,400-5,500) to secure their release.
Police began their investigation after receiving a complaint from the wife of one of the kidnapped men who lives in the northern city of Lugo.
They received a tip from someone in Morocco who said two men were being held at an apartment in Algeciras and when they raided the flat they found the two kidnapped migrants.
"Both kidnapped men had suffered injuries, and one of them even told the officers that he had thought of throwing himself out the window if they were not freed by police," the statement.
Police arrested the two suspected kidnappers, one was outside the apartment and the other inside.
Thousands of migrants tried to reach Spain from Morocco each year.
Many try to smuggle themselves across the border to Ceuta and Melilla, two tiny Spanish territories that border Morocco, hidden in cars while others cross the Mediterranean in flimsy boats or hidden on ferries.