you can take it back to the store depending on how long you've had teh food.
Since hamster food is mostly carbs i believe (the pellet stuff), just like rice it prob gets infested with the black bugs. What happens is while the food is processed and cleaned sometimes stray eggs of these black bugs will be missed. These bugs(at least the ones in the rice) aren't poisonous at all.
A lot of times we don't notice it if we use the product within say a couple weeks or so(roughly how long a 40lb bag of rice lasts my family). So the harmless eggs just get cooked/ eaten/ rinsed away.
We only notice bugs in our grains when it has been sitting either in the store for too long or in our house too long. The bag could be infested even if it was NEVER opened, but we notice it since after the time period the eggs have hatched and then have started eating the food and then of course reproducing.
If it was a long time you had it and then opened it, nothing you can do really, unless you know where ur friend bought the food from and they have a really long return period.
If it was on the shelf awhiles and you just bought it recently then you can definitely and should definitely be entitled to a refund
if the bag was open already when you got it, then sorry to say, but you just gotta buy new food. Although i doubt the black bugs are harmful, i still wouldn't feed ur hamster them.
So yeah i don't think the food came from your hamsters cage, it came from the bag itself.
The best thing for you to do is what your planning to do. Empty all the bedding and jst do a full clean up. then keep then store you food in an air tight container or even a casual bucket with a rubber cover is fine. It will also make it easier to check the food. What i use to do with my cat food/rice for awhiles is run my hand through the food in the bucket to see if any black bugs start moving around. Lately in the past year i haven't seen any bugs in mine so i sorta jus stopped.