This concept literally blows my mind. G-d created evil so that we could have freedom of choice. G-d also created evil to have perfect balance between good and evil.
Judah convinced his brothers to sell Joseph as a slave. They then sent Joseph’s robe, smeared with goat blood, to Jacob. Jacob mourned for Joseph inconsolably. The brothers then shunned Judah for not insisting that they return Joseph to Jacob. Judah left Hebron, married, and had three sons. He married off his eldest to Tamar, who was anxious to bear Judah’s descendants. When Judah’s eldest died, he married his second son to her; when the second son also died, Judah was afraid to marry his third son to her. Tamar disguised herself as a prostitute in order to trick Judah into having children by her.
[Judah] named [Tamar’s firstborn] Peretz. Genesis 38:29
The Messiah is descended from Judah through his and Tamar’s son Peretz. In order to understand why it was necessary for the Messiah to enter the world in such a seemingly scandalous way, we need to recall that G‑d only created evil in order for there to be free choice. In order for free choice to exist, the forces of evil and the forces of good have to be perfectly balanced.
When the messianic line was about to enter the world, the forces of evil “argued” that the balance was about to be tipped against them. Therefore, the union that would bear the ancestor of the Messiah had to occur in a way that the forces of evil would consider beneficial to them. Just as in military strategy, an army sometimes pretends to retreat in order to draw the enemy into a vulnerable position, the forces of holiness here yielded a seeming victory to the forces of evil in the form of this seemingly sinful act, in order to gain the upper hand.1 Derech Mitzvotecha 32a–32b; Or HaTorah, Bereishit, vol. 6, 1096b–1097a.