CAIRO — Militants detonated a bomb inside a crowded mosque in the Sinai Peninsula on Friday and then sprayed gunfire on panicked worshipers as they fled, killing at least 305 people and wounding at least 128 others. Officials called it the deadliest terrorist attack in Egypt’s modern history.

The scale and ruthlessness of the assault, in an area racked by an Islamist insurgency, sent shock waves across the nation — not just for the number of deaths but also for the choice of target. Attacks on mosques are rare in Egypt, where the Islamic State has targeted Coptic Christian churches and pilgrims but avoided Muslim places of worship.

The attack injected a new element into Egypt’s struggle with militants because most of the victims were Sufi Muslims, who practice a mystical form of Islam that the Islamic State and other Sunni extremist groups deem heretical. And it underscored the failure of President Abdel Fattah el-Sisi, who has justified his harsh crackdown on political freedom in the name of crushing Islamic militancy, to deliver on his promises of security.

“The scene was horrific,” said Ibrahim Sheteewi, a resident of Bir al-Abed, the small north Sinai town where the attack took place. “The bodies were scattered on the ground outside the mosque. I hope God punishes them for this.”