The magnetic fields of Earth and Jupiter, along with those of rapidly rotating, low-mass stars, are generated by convection-driven dynamos that may operate similarly (the slowly rotating Sun generates its field through a different dynamo mechanism). The field strengths of planets and stars vary over three orders of magnitude, but the critical factor causing that variation has hitherto been unclear. Here we report an extension of a scaling law derived from geodynamo models to rapidly rotating stars that have strong density stratification. The unifying principle in the scaling law is that the energy flux available for generating the magnetic field sets the field strength. Our scaling law fits the observed field strengths of Earth, Jupiter, young contracting stars and rapidly rotating low-mass stars, despite vast differences in the physical conditions of the objects. We predict that the field strengths of rapidly rotating brown dwarfs and massive extrasolar planets are high enough to make them observable.