“It was not an outsider hacking in, but an insider,” he said.

General Alexander spoke in defense of the N.S.A.'s surveillance programs, including its collection of a vast database of information about all phone calls made and received in the United States. “You need a haystack to find a needle,” he said, even while acknowledging that he was open to the idea that the nation’s telecommunications companies, rather than the government, should retain control of the data.

But at the security forum, of which The New York Times is a media sponsor, General Alexander also revealed for the first time that President Obama, shortly after taking office, had been surprised by the number of errors the agency made, which resulted in what General Alexander called the inadvertent collection of information about American citizens.

“When the president first came on board, we had a huge set of mistakes that we were working through in 2009,” he told the audience. “He said essentially, ‘I can see the value of these, but how do we ensure that we get these within compliance and that everything is exactly right?' ” That suggested that Mr. Obama had questioned the execution of a program he had inherited from President George W. Bush, but satisfied himself by having the N.S.A. set up what the general called a “directorate of compliance,” an internal watchdog group.

Both Mr. Carter and General Alexander said that the military has begun to deploy roughly 4,000 people in the Pentagon’s first units devoted to conducting cyberoffense and -defense operations, a new mission that formalizes America’s use of a class of weapons that the Obama administration has rarely discussed in public.

“I wanted to start this fast,” Mr. Carter said. “Fundamentally, we’re spending everything we can think about spending intelligently for, notwithstanding our budget hassles, because this is an area that we are protecting even as other military capabilities will be cut.”