To unlock an iPhone you need the NCK which is a unique 15 digit key. Those keys for unlocking are sitting on Apples servers and send to the iPhone via iTunes while the iPhone is connected to the Mac/PC.
Each iPhone has a unique HWID, NORID, CHIPID, (id's embedded in the iphone hardware/chips and unique to each phone), the NCK is only working with the one iPhone where the above are matching. The NCK does not unlock any other iPhone.
Trying to bruteforce the NCK would take years even on high-end computers (NCK Brute Force - The iPhone Wiki
Trying to guess the NCK is limited aswell, After 5 or so unsuccessful attemts, the iPhone becomes permanently locked to the carrier - unless you're feeling really, really lucky, I wouldn't try it.
Apple has HWID, NORID, CHIPID... of all iPhones sold in countries, where the iPhone has to be sold unlocked (About activating iPhone 3G with a wireless carrier
). So once a phone of those is connected via iTunes, the apple servers check HWID, NORID, CHIPID and compare it to their database. If the matching iPhone is marked "factory unlocked" the Apple servers send the unique NCK for this iPhone.