Keygens generate a serial number and sometimes an activation number so you can get a program for free using that serial number and/or activation number. The level of coding and knowledge to create one is well beyond me.
They work because the programmer cracked the algorithm required in order to create each individual key. Different programmers use different algorithms to create keys. Once the algorithm is cracked by the programmer it is as simple is putting that into the program. Not all are the same though so that is why each program needs a separate keygen.