BALTIMORE — A troubled former National Security Agency contractor who spent two decades stuffing his home, car and garden shed with highly classified documents was sentenced on Friday to nine years in prison in a case that exposed a shocking laxity in security at the N.S.A. and other secret government facilities.

Investigators originally feared that the contractor, Harold T. Martin III, might have passed or sold secrets to a foreign power or to a still-mysterious group calling itself the Shadow Brokers, which released dangerous N.S.A. hacking tools online in 2016 and 2017. But they appear to have concluded that his amassing of secrets was a symptom of a quirky, disturbed mind, not evidence that Mr. Martin, a 54-year-old Navy veteran, wanted to betray his country.

In March, Mr. Martin pleaded guilty to a single count of willful retention of national defense information. Prosecutors and defense lawyers agreed on the sentence, which was approved by United States District Judge Richard D. Bennett.

Mr. Martin’s lawyer, James Wyda, said his client had an “autism spectrum disorder” and had experienced difficulty forming and keeping relationships since childhood. As a result, the lawyer said, he had sought meaning and validation in his work as a contractor at the N.S.A. and other agencies, bringing home documents to work on at night.