For nearly three weeks, Baltimore has struggled with a cyberattack by digital extortionists that has frozen thousands of computers, shut down email and disrupted real estate sales, water bills, health alerts and many other services.

But here is what frustrated city employees and residents do not know: A key component of the malware that cybercriminals used in the attack was developed at taxpayer expense a short drive down the Baltimore-Washington Parkway at the National Security Agency, according to security experts briefed on the case.

Since 2017, when the N.S.A. lost control of the tool, EternalBlue, it has been picked up by state hackers in North Korea, Russia and, more recently, China, to cut a path of destruction around the world, leaving billions of dollars in damage. But over the past year, the cyberweapon has boomeranged back and is now showing up in the N.S.A.’s own backyard.

It is not just in Baltimore. Security experts say EternalBlue attacks have reached a high, and cybercriminals are zeroing in on vulnerable American towns and cities, from Pennsylvania to Texas, paralyzing local governments and driving up costs.