The best way to handle this is to refuse to keep secrets or enter into gossip. If that's impossible, then at least refuse to accidentally promise to keep secrets.
Hey, Matthew, did you hear about B? I mean, don't tell anyone I told you, but --
"Sorry A, I don't want to hear something I can't tell anyone."
Or, at the end of a long conversation in which you learned a LOT (whether you wanted to or not)
Man, good stuff eh? But listen, don't tell anyone ok, because if this got out B might get fired or even divorced.
"Sorry A, if you wanted this off the record you should have said so. I'm not going to blab it around to everyone, but if I get asked, I'm not lying about it."
The more you use these two sentences the more others will think twice before putting you in this position.
As for reacting when B tells you something you already know, a simple "Really?" or "Oh my" or "I'm sorry to hear that" is all that's needed before you discuss it exactly as you would whether you knew already or not. "What are you going to do?" or "Is it serious?" or "Is there anything I can do to help?" for example.
If someone asks you "did you already know that X?" I can't see lying being a better approach than the truth. You could try "I heard some rumours that could be interpreted like that, but I didn't know for sure one way or the other." That's as close to lying as I would be willing to get. You don't have to answer, of course: you can reply "Why? Is that's what's been going on?" or "What? Are you saying X?" and then go on as in the case where they tell you something you already knew.
My answer to a gossiping question may also be relevant here.