If someone accumulates wealth through usury, forgery, gambling, prohibited games, or in any other haram manner in order to build a mosque, establish a charitable foundation, or to do any other good work, the guilt of having done what is haram will not be lifted from because of the goodness of his objective; in Islam good aims and intentions have no effect in lessening the sinfulness of what is haram. This is what the Prophet (peace be on him) taught us when he said:
Allah is good and does not accept anytbut good, and Allah has commanded the Believers, as He commanded His messengers, saying 'O you messengers! Eat of whatever is good and work righteousness. Indeed, I am aware of what you do.' (The Qur'an 35:31.)
He also said,
'O you who believe! Eat of the good things which We provide for you.' (2:172.)
The Prophet (peace be on him) then said,
A man travels far, unkempt and dust-stained (for hajj, umrah, or the like), raising his hands to the sky (and saying), 'O Lord! O Lord!' while eating what was haram, drinking what was haram, wearing what was haram, and nourishing himself through haram means. How then could his prayers be accepted? (Reported by Muslim and al-Tirmidhi on the authority of Abu Hurairah.)
He also said:
'If anyone amasses wealth through haram means and then gives charity from it, there is no regard for him and the burden of sin remains.' (Reported by Ibn Khazimah, Ibn Hibban, and al-Hakim on the authority of Abu Hurairah)
Again he said:
'If a person earns property through haram means and then gives charity, it will not be accepted (by Allah); if he spends it there will be no blessing on it; and if he leaves it behind (at his death) it will be his provision in the Fire. Indeed, Allah Ta'ala does not obliterate one bad deed by another bad deed, but He cancels out a bad deed by a good deed. An unclean thing does not wipe away another unclean thing.' (Reported by Ahmad and others on the authority of Ibn Mas'ood.)