It is understandable that federal investigators want to unlock an iPhone used by one of the attackers who killed 14 people in San Bernardino, Calif., in December. And it’s understandable that the government would turn to Apple for help. But Apple is doing the right thing in challenging the federal court ruling requiring that it comply.

In an order issued on Tuesday, Magistrate Judge Sheri Pym says Apple must create new software that would bypass security features on the iPhone used by the terrorist, Syed Rizwan Farook. That would allow the Federal Bureau of Investigation to unlock the device and retrieve the pictures, messages and other data on it. Her ruling was based on the All Writs Act of 1789, which is used to require people or businesses not involved in a case to execute court orders. Another federal magistrate judge in New York is considering a similar request to unlock an iPhone in a narcotics case.

Law enforcement agencies have a legitimate need for evidence, which is all the more pressing in terrorism cases. But the Constitution and the nation’s laws limit how investigators and prosecutors can collect evidence. In a 1977 case involving the New York Telephone Company, the Supreme Court said the government could not compel a third party that is not involved in a crime to assist law enforcement if doing so would place “unreasonable burdens” on it. Judge Pym’s order requiring Apple to create software to subvert the security features of an iPhone places just such a burden on the company.

Apple has already given the F.B.I. data from the phone that was backed up and stored on its iCloud service; the last backup was made about a month before the attacks. But the company’s chief executive, Timothy Cook, has said that requiring it to create software to bypass a feature that causes the phone to erase its data if 10 incorrect passwords are entered would set a dangerous precedent and could undermine the security of its devices. The Department of Justice has argued that the software would be used on that phone only and notes that Apple has previously helped law enforcement unlock phones. The company changed how it encrypts phones after the surveillance revelations by Edward Snowden.