Characterization of infinite divisibility by duality formulas. Application to Lévy processes and random measures