I was lucky enough to attend a meeting organised by the British Society for the History of Mathematics on "The History of Cryptography and Coding". It was a quite exceptional meeting - six excellent talks. As one of the other audience members said, I learned something from every talk, and a lot from several talks. (Anyone who goes to these events will know that this isn't always the case.)
The final talk, by Clifford Cocks on the discoveries of the public key cryptography, was fascinating in many respects. (Cocks was one of the people at GCHQ who discovered both the Diffie-Hellman key exchange method and the Rivest-Shamir-Adleman (RSA) algorithm before those after whom the ideas are named, but this wasn't known until GCHQ made it public over 25 years after the event.) Cocks told us about the (different) reasons why the British and American discoverers were looking for these methods. I was particularly struck by his insights into the creative processes that led to the discoveries.
In 1970 James Ellis at GCHQ had the idea of public-key cryptography. Many people at GCHQ tried to find a way to implement it, without success. Cocks suggested that this was because of "tunnel vision" - because Ellis's paper suggested using look-up tables, everyone was focused on that idea. Cocks had just arrived at GCHQ from university, and his mentor mentioned Ellis's problem to him, but described it in general terms without mentioning look-up tables. Without having been led in a wrong direction, Cocks quickly came up with the idea of using factorisation, and the problem was solved. (When Cocks told his colleague and housemate Malcolm Williamson about his paper, Williamson overnight worked up the idea of using the discrete logarithm problem, anticipating Diffie and Hellman.)
Cocks also told us about how Diffie was working on these discoveries having left his academic job, supporting himself on his savings - something which I don't recall knowing.
Then Cocks told us about Rivest, Shamir and Adleman's discovery of RSA. They had tried about 30 ideas, none of which worked. Then after a Passover meal at which alcohol flowed freely, Rivest had the big idea, wrote it down, and checked the next morning to see if it still worked.
I think these stories shed some light on mathematical creativity. It needs hard work, of course, but it also needs flexibility. Cocks (by his modest account) had the advantage over his colleagues that his mind wasn't conditioned by an unproductive idea. Rivest's solution came after a break from thinking about it. Of course, there are many other examples - Poincaré's inspiration as he was getting on a bus is the standard one - but it is always interesting to hear how great mathematical discoveries came about, and to hear this story from Cocks himself was a wonderful privilege.