Bluing is a process for finishing steel or stainless steel which provides some degree of protection against unwanted corrosion, a bit of scratch resistance and darkens the metal for aesthetic or anti-glare purposes. It is most famously used on the metal components of firearms, and prior to the modern industrial availability of plating and more durable high-tech coatings, bluing was the 'industry standard' for protecting guns.
In a way, bluing is simply prophylactic rusting. This is why it only works on steel or other iron alloys. There are several types of bluing; the most common are known as 'cold' and 'hot' bluing. Cold bluing involves dipping the part to be protected in an acid and allowing it to corrode, then dunking the part in boiling water to remove the acid from the surface and to arrest the corrosion process. Once the boiling was done, the part was 'carded' or brushed off using a very fine wire brush. Once the part was smooth, this process was repeated until the part ceased to darken in color, indicating that the entire surface has been properly blued.
'Hot' bluing involves placing the part in a solution of boiling water and various reactants - sodium hydroxide, potassium nitrate or others - until the distinctive coating and color form.
Bluing corrodes the outermost layers of the metal in such a way that the iron in the metal forms magnetite - a black oxide with the formula Fe3O4. Unlike regular iron corrosion (rust) which is considered a red oxide, this form of corrosion causes very little change in the volume of the corroded iron; as a result it does not flake off the rest of the part, and retains a strong bond with the material. Since the surface is 'pre-rusted', water will not be able to easily penetrate this coating of rust and continue to corrode the metal. Bluing does work to reduce corrosion, but is most effective when the metal part so treated is regularly treated with oil to seal out as much air and moisture from the surface as possible.
If you're really interested in gun treatments for corrosion protection, the U.S. Department of Defense is your friend, for they have made a manual on this very subject available.