Am writing a program which needs PCs to communicate with each other. Have got my head around public key encryption and am succesfully encrypting and decrypting messages using public keys, and locally stored private keys. Each PC knows every other PC's public keys.
However I can't quite understand the concept of signing (which I need to do so nobody can impersonate another PC, and a message can be KNOWN to come from a particular PC.) I understand that a hash is taken of the message (before encryption) by the sender and then the hash is encrypted using the sender's private key. The receiver then decrypts the message, hashes it and also encrypts the hash using the sender's public key. This encrypted hash is then compared to the encrypted hash sent by the sender. If the two match the sender is guaranteed to be who he says he is.
However - couldn't a third party, knowing the sender's public key, impersonate him by signing a message using the sender's public key? When the receiver encrypts the hash, also using the sender's public key, the two will match, and the receiver will be deceived into beleiving the source is verified. I am new to this! It's very confusing.