Contrary to the common belief that mobility makes security more difficult to achieve, we show that node mobility can, in fact, be useful to provide security in ad hoc networks. We propose a technique in which security associations between nodes are established, when they are in the vicinity of each other, by exchanging appropriate cryptographic material. We show that this technique is generic, by explaining its application to fully self-organized ad hoc networks and to ad hoc networks placed under an (off-line) authority. We also propose an extension of this basic mechanism, in which a security association can be established with the help of a "friend". We show that our mechanism can work in any network configuration and that the time necessary to set up the security associations is strongly influenced by several factors, including the size of the deployment area, the mobility patterns, and the number of friends; we provide a detailed investigation of this influence.