Why would a security agency distribute research funds?
Let me just add a bit more context as a pure mathematician previously funded by the NSA, and in particular, respond to the question "What does a security agency has to do with distributing funds?"  The first point is, they actually farm out most of the decision making to the American Mathematical Society (as described here).  That still raises the question of why policy makers think routing the money through the NSA makes sense in the first place.  The cynic in me points out that though lots of this research could easily be funded through civilian agencies (for example, NSF), it's a lot easier to pass "defense spending" through congress, and you get fewer questions from ignorant congressmen who like to make fun of grants based on their titles.

On the other hand, that still requires somebody in the NSA thinking that requesting this funding is worthwhile.  My reading (this is not based on any detailed knowledge of policy makers' thoughts, just general supposition) is this: the NSA is the largest employer of mathematicians in the world, much larger than any university or scholarly society.  You would get an even more impressive number if you included other branches of the US Department of Defense, and contractors like IDA.  They thus have a vested interest in making sure more Americans get advanced mathematical training (a lot of their jobs are in practice only open to US citizens, due to security clearances), and keep in mind the possibility of working for the NSA.  

Giving grants to mathematicians is probably an inefficient method for this (some of the money goes to graduate students directly as salary or travel funding, some to universities as overhead, encouraging them to keep professors on their staff and run graduate programs), but it's also very cheap in the grand scheme of things. I'm sure they also do occasionally benefit from the mathematical results (while they have a reasonably broad program, they don't give grants in all areas of math).  

There's also tons of other grants coming from the DOD: DARPA, the Army, Navy and Air Force all have their own research offices, and the DOD has its own graduate fellowship program.  In all cases, some of the research is directly connected to military needs, but quite a bit is just predicated on the idea that a strong a well-trained pool of scientists can be very important for national defense.  I think ultimately, this grew out the experience of World War II (and the Cold War) where this was undisputedly the case.