The US justice department cannot use a 227-year-old law to force Apple to provide the FBI with access to locked iPhone data, a judge ruled.

It dealt a blow to the government in its battle with the company over privacy and public safety.

The ruling by US Magistrate Judge James Orenstein applied narrowly to one drug case in Brooklyn, New York City.

But it gives support to the company in its fight against a California judge's order that it create specialised software to help the FBI hack into an iPhone linked to the San Bernardino terrorism investigation.

Mr Orenstein belittled some government arguments, saying lawyers were stretching an old law "to produce impermissibly absurd results".

He rejected their claims that Apple was only concerned with public relations, and said he found no limit on how far the government would go to require a person or company to violate the most deeply-rooted values.

Both cases hinge partly on whether a law written long before the computer age, the 1789 All Writs Act, could be used to compel Apple to co-operate with efforts to retrieve data from encrypted phones.

Mr Orenstein said the question was not whether the government should be able to force Apple to help it unlock a specific device, but whether the Act resolved the issue.

"I conclude that it does not," he wrote.

Apple's opposition to the government's tactics has evoked a national debate over digital privacy rights and national security.

On Thursday, the Cupertino, California-based company formally objected to the California order, accusing the government of seeking "dangerous power" through the courts and of trampling on the company's constitutional rights.

The separate California case involves an iPhone 5C owned by San Bernardino County and used by Syed Farook, who was a health inspector.

Farook and his wife Tashfeen Malik killed 14 people during a December 2 attack that was at least partly inspired by the Islamic State group. The couple died later in a gun battle with police.

The New York case features a government request far less onerous for Apple and its mobile phone technology as the extraction technique exists for the older operating system and it has been used some 70 times before to assist investigators.

Since late 2014, that physical extraction technique has not existed on newer iPhones.

The court ruling came a day before a congressional hearing that will include testimony from FBI Director James Comey and Apple General Counsel Bruce Sewell on encryption and "balancing Americans' security and privacy".

The justice department said it was disappointed by the ruling and plans to appeal.

Sign up to our free newsletters

Get the best updates straight to your inbox:
Please select at least one mailing list.

You can unsubscribe at any time by clicking the link in the footer of our emails. We use Mailchimp as our marketing platform. By subscribing, you acknowledge that your information will be transferred to Mailchimp for processing.