That's Rumpelstiltskin, a German fairy tale.
In order to appear superior, a miller lies to the king, telling him that his daughter can spin straw into gold (some versions make the miller's daughter blonde and describe the "straw-into-gold" claim as a careless boast the miller makes about the way his daughter's straw-like blond hair takes on a gold-like lustre when sunshine strikes it). The king calls for the girl, shuts her in a tower room filled with straw and a spinning wheel, and demands she spin the straw into gold by morning or he will cut off her head (other versions have the king threatening to lock her up in a dungeon forever). When she has given up all hope, an imp-like creature appears in the room and spins the straw into gold in return for her necklace (since he only comes to people seeking a deal/trade). When next morning the king takes the girl to a larger room filled with straw to repeat the feat, the imp once again spins, in return for the girl's ring. On the third day, when the girl has been taken to an even larger room filled with straw and told by the king that he will marry her if she can fill this room with gold or execute her if she cannot, the girl has nothing left with which to pay the strange creature. He extracts from her a promise that she will give him her firstborn child and so he spins the straw into gold a final time (In some versions, the imp appears and begins to turn the straw into gold, paying no heed to the girl's protests that she has nothing to pay him with; when he finishes the task, he states that the price is her first child, and the horrified girl objects because she never agreed to this arrangement).
The king keeps his promise to marry the miller's daughter, but when their first child is born, the imp returns to claim his payment: "Now give me what you promised." She offers him all the wealth she has to keep the child, but the imp has no interest in her riches.
He finally consents to give up his claim to the child if she can guess his name within three days (some versions have the imp limiting the number of daily guesses to three and hence the total number of guesses allowed to a maximum of nine).
More details can be found in the linked wiki.
In the end, in the original German version, the girl finds out the imp's name by stalking and spying on him as he sings about himself. In the Politically Correct Bedtime Stories version of the tale, the imp simply forgets that he still has his nametag on his shirt, so the girl finds it out via the power of literacy.