Attorney General Lord Goldsmith is to step down after six years in office.
Lord Goldsmith had given "outstanding service" to the country
He said he will leave his post next week - as Tony Blair quits after 10 years as prime minister.
Lord Goldsmith said he had been "immensely privileged" to serve what had been a record period of time for a Labour attorney general.
Tony Blair praised the work of Lord Goldsmith and said he could look at his time as attorney general with "personal and professional pride".
Lord Goldsmith said he had wanted to move on for some time and had told Mr Blair and Gordon Brown he believed that now was the right time to make that move.
In his resignation letter to Mr Blair, the government's legal adviser acknowledged the "challenge" of advising on the legality of the war in Iraq.
There was controversy over his advice that the 2003 invasion would be legal under international law amid claims he changed it under political pressure - something which he vehemently denies.
In his letter, Lord Goldsmith wrote of the past six years: "It hardly needs saying that during that period we have faced a host of challenges, many of them raising important legal questions.
"These include two conflicts in Iraq and Afghanistan, the fight against terrorism, the balancing of individual rights and collective security, continuing constitutional reform and the great progress towards peace and stability in Northern Ireland.
"I have been privileged to play my part in meeting these challenges."
In his written reply, the prime minister said Lord Goldsmith had "made a huge contribution" to the government's success in improving the criminal justice system.
Prime Minister-in-waiting Mr Brown said Lord Goldsmith had given "outstanding service" to the country.
"His contribution to the country and this government has been immense, not least through transforming the Crown Prosecution Service," he said.
"It is with my regret that he has made his personal decision to step down."
Lord Goldsmith will take part in a review of legal and other aspects of citizenship for Mr Brown.
Liberal Democrat president and legal spokesman Simon Hughes said Lord Goldsmith would be remembered as "one of the most controversial attorney generals in post-war British politics".
"He will always share responsibility for the decision to invade Iraq and to drop the investigation into alleged corrupt dealings between BAE and the Saudi government in connection with Britain's biggest ever defence contract," he said.
Mr Hughes called for "different procedures" for decisions about any future prosecution on cash-for-honours, and "new arrangements" for the role and accountability of law officers.
"From now on, all future attorney generals should take office only if Parliament agrees with the prime minister's choice," he added.