The director of GCHQ has apologised for historic prejudice against homosexuals by the agency and the "horrifying" treatment of Alan Turing.
Robert Hannigan said the secret service failed to learn from its mistaken treatment of the genius and archaic attitudes had persisted for decades, stifling the careers of brilliant minds.
It included a ban on homosexuals joining the organisation that remained in place into the 1990s, causing long-lasting psychological damage to those who found themselves outed, interrogated and ostracised over their sexuality.
In a rare public appearance at a conference hosted by Stonewall, the digital espionage chief told how a former spy, "Ian", who was forced out of the service on suspicion of being gay in the 1960s, had urged him to apologise for his treatment.
He said: "I am happy to do so today and to say how sorry I am that he and so many others were treated in this way, right up until the 1990s when the policy was rightly changed.
"The fact that it was common practice for decades reflected the intolerance of the times and the pressures of the Cold War, but it does not make it any less wrong and we should apologise for it.
"Their suffering was our loss and it was the nation's loss too because we cannot know what Ian and others who were dismissed would have gone on to do and achieve. We did not learn our lesson from Turing."
Known as the father of the modern computer, Turing led the famous Bletchley Park codebreakers who cracked the Enigma, an encryption device used by the Nazis.
Despite his ground-breaking work that is now recognised to have shortened the Second World War, he was hounded from the secret service over his sexuality.
Turing faced a criminal charge of indecency over his relationship with another man and after conviction in 1952 was ordered to undergo chemical castration.
In 1954 he took his own life by eating an apple laced with cyanide. In 2013 he received a royal pardon, although the tragic tale of how the war hero's life ended had become "sadly famous", Mr Hannigan said.
"In the horrifying story of his treatment, a small ray of light is that he was not abandoned by all of his colleagues at GCHQ - many stood by him," he added.
More than half a century on GCHQ now relies on those who "dare to think differently and be different", he said.
It included hiring spies on the autistic spectrum, with Aspergers or other syndromes, who he described as "precious assets" for protecting national security.
Mr Hannigan told the Stonewall Workplace Conference in London that GCHQ supported the charity in "defending and promoting tolerance and acceptance without exception".