Simulating Z2 gauge theory and Kitaev's toric code