What you're asking to do is possible but quite difficult. First of all you need to understand a few ideas so here we go.
Firstly, signature schemes. You've no doubt looked at digital signature schemes on the web and you might rightly ask - so why don't you just sign the whole file? Well, the answer to that is that in at least the case of RSA, you open yourself up to existential key-only forgery attacks. That is, I can generate valid signatures for different message pairs just by knowing your public key.
The solution to this is to use message digests - hashes, in other words. A cryptographically secure hash function is one that not only has preimage, but collision resistance.
So now to what you (and the NSA, and the entire Russian criminal underworld) want to do. You want to pass off a signed file as having a valid digital signature using a digital signature you found somewhere else. Okay. There are two things you can do:
- You can take their public key, generate a valid message/signature pair, then try to find a pre-image of the hash that actually works. Good luck. There are no pre-image attacks on even MD5, that I know of.
- You can try to find a collision with the hash value they used, and just cat the signature on the end.
Number 2 is exactly what the authors of the flame malware did - they took a valid signature and exploited an MD5 collision to make it valid.
With a whole executable that works, I hear you say? How did you not segfault?! Well, hold up a minute. See, digital signatures underpin the entire chain of certificates from root CAs down to your code. You trust root CAs because they're in your local store. You trust things they sign because their signatures are valid. Those "things" can be intermediate certificates, which can then sign other objects. You trust the chain because when you check each signature, they're all valid signatures that can only be made with the private key.
So rather than find a collision with the hash of the binary, do it with a hash of another certificate and use that collision to let you generate a cert that can sign anything and be valid in the chain.
the NSA someone already did this with MD5, the world has discovered the problem. MD5 certificates are a thing of the past now and SHA1 is even being sunset, but, just in case. To the best of my knowledge, right now, nobody knows how to generate valid SHA256 collisions on demand.
So, you need to a) target the certificate chain, as ASN.1 parsers are evil and b) break SHA256.
If you want to try to reproduce this, I would recommend a copy of Windows XP which still accepts MD5 certificates (don't let it do Windows update), generate some MD5 certs with openssl then try to reproduce the flame outcome :)