Deep inside an old Tehran political prison, three turns off a dark corridor and through a small gap, lies a bleak cell for solitary confinement. Too narrow for a prisoner to extend his arms, it was once the cell of the man who today holds the official title in Iran, "God's deputy on earth."

Scratched into the blackened paint is a hopeless verse about "the prison ashamed of the face of the liberated."

It was here in the 1970s that opponents of the American-backed Mohammad Reza Shah Pahlavi were held and tortured by the SAVAK secret police, as popular anger outside swelled inevitably toward the 1979 Islamic revolution. That event would oust the shah and usher in a self-proclaimed "government of God."

The downtown prison has since been turned into a museum called Ebrat, which means "lesson" or "example." Its ghoulish displays are a stark reminder of just one critical influence – a wary anti-Americanism – on the thinking of its most famous inmate, supreme leader Ayatollah Ali Khamenei.

Holding absolute power at the top of Iran's theocratic regime today, Mr. Khamenei will make the decisions that yield war or peace, determine détente with the United States or another generation of hostility, and dictate how far Iran goes toward a nuclear weapons capability. Few other global actors will be more important to understand as President Obama begins a second term, with Iran dominating issues across the Middle East and beyond.

Yet to many, Khamenei, whose black turban denotes a direct line of descent from Islam's prophet Muhammad, remains an enigma. A bookish revolutionary cleric with a passion for poetry, who years ago wore his clerical collar in the style of the "chic sheikhs," he was once considered a liberal, and on one occasion in the late 1980s even challenged the absolute power of the post he now holds.

Since taking the top spot in 1989, Khamenei has been a calculating player on the world stage, never leaving Iran but claiming leadership, with endless rhetorical flourish, of a global Islamic revolution. He has survived assassination attempts, remains deeply paranoid about his personal security, and is preoccupied with what he sees as the threat to the Islamic republic from Velvet Revolution-style protests and "Westoxication." And despite having lesser clerical credentials than many of Iran's most senior theologians, who have chafed at Khamenei's role as velayat-e faqih – the supreme religious ruler, who is meant to be infallible – he has godfathered the unruly and often vicious political scene inside Iran for nearly a quarter century.

Today, Khamenei presents himself as an uncompromising commander of an ever-strengthening Iran-led "Axis of Resistance," locked in battle against what he lambasts as the declining "arrogant" power of the US, other Western nations, and Israel.

Yet Iran also faces a host of US-led sanctions that are targeting its economy, choking its oil exports, and cutting off its central bank to pressure the country into halting its nuclear program. Does Khamenei see a way beyond the covert war that has shaken Tehran in recent years with the assassination of nuclear scientists, unexplained explosions, and computer viruses aimed at Iran's nuclear facilities – all of which he blames on the US and Israel? And what will he do if Israel or the US bombs the country's nuclear sites?

While Khamenei may deeply distrust the West and see in all things a policy of regime change by Washington, Iran's supreme leader has often shown a pragmatic streak. He has long placed survival of the Islamic regime above all else. And his officials are now signaling a willingness to talk, and even to deal with the US – if the other side is ready, too.

"We should think of Khamenei as a person that has been swayed in different directions, depending on circumstances," says Farideh Farhi, an Iran analyst at the University of Hawaii at Manoa. Khamenei's tremendous distrust of America is due to his long contact with Washington's anti-Iran policies, "not necessarily because of a reflexive anti-Americanism" that is "part of his DNA," says Ms. Farhi. "Yes, there is an incorrigibility on his part. But his history also shows that when he sees a possibility – a potential for a change in the American position – he assents to [exploring] it."

* * *

Deciphering Khamenei's worldview is possible by examining key moments in the supreme leader's history, in word and deed. Among the hundreds of framed mug shots that line walls at the prison museum, for example, is that of a younger, unsmiling Khamenei. He has a thick black beard, and his eyes look through large, slightly askew glasses, unimpressed and unflinching.

The picture was taken during one of Khamenei's six arrests. Painted over his prison number is the Persian year of his incarceration, which equates to 1974 – the same year Amnesty International reported Iran under the shah to have a "history of torture that is beyond belief."

These days student tours follow a trail of blood-red footprints painted on the floor from one torture room to the next, which are meant to illustrate the secret police's favored practice of whipping feet with metal cables and braided whips. No opportunity is missed to demonstrate a link between the pain inflicted upon Iranians, and the American CIA and Israeli Mossad trainers of SAVAK.

Many of the life-size torturers are made to look unmistakably like American agents, taller and lighter skinned, and wearing ties and suspenders. They stand over wax-figure victims that drip fake blood from their wounds. Some of the prisoners hang upside down, their bodies burned and lacerated.

SAVAK's old-school aim was to break its victims' will to resist, but the pain the torturers inflicted often just galvanized hatred of the shah and his American backers.

"US support for the dictatorial and suppressive rule of the shah was critical" to shaping Khamenei's views, says Seyed Hossein Mousavian, a former Iranian ambassador and member of its national security council now at Princeton University in New Jersey, who met with Khamenei several times. "Ayatollah Khamenei's struggle against the shah dates back 15 years prior to the revolution. During this time he was repeatedly tortured, held in detention, and exiled. He saw in this repression the role of the US [and] their blatant support and hypocrisy."

Anti-Americanism has been a pillar of the revolution, codified by the 1979 takeover of the US Embassy in Tehran, in which 52 American diplomats were held hostage for 444 days. In the decades since, attempts have been made by both the US and Iran – authorized on the Iranian side by Khamenei – to find a less hostile modus vivendi. All have failed, victims of mismatched expectations, or miscommunication, or spoiler actions by hard-liners bent on preventing any deal. In some cases, it was simply one side unwilling to allow the other side anything it might use to declare a "victory."

It has all served to calcify levels of distrust. In 2008 Khamenei declared that "there hasn't been a day in which America has had good intentions toward Iran." Marking the anniversary of the embassy seizure, he said Iran's problem with the US was not over "one or two" issues that "we can resolve by sitting down and negotiating. The problem is like a matter of life and death."

* * *

An unlikely site of pilgrimage is nestled in a decrepit north Tehran neighborhood, where small electrical and furniture shops give way to the steep rocky outcrops of the Alborz Mountains. It is here in Jamaran where the father of Iran's revolution, Ayatollah Ruhollah Khomeini, chose to live and preach after returning from exile in 1979. Existing ascetically on bread and yogurt, onions and garlic, he presided thunderously over an Islamic resurgence that shook the world.

It was Mr. Khomeini whose cutting words from exile galvanized anger against the shah, declaring in 1971, for example, that the term "king of kings," used by Iranian monarchs, was the "most hated of all titles in the sight of God." Their crimes "have blackened the pages of history," Khomeini railed, as the shah marked the 2,500th anniversary of the Persian Empire with a lavish culinary spectacle while some Iranians were starving.

Khomeini's cramped home in Jamaran was connected to a small prayer hall with high windows and meager space for kneeling believers. Herds of visiting schoolchildren file through the site today, where a brass plaque states that this "very modest and humble house" became the center for the hearts of "millions of Muslims" and "disturbed the sweet dreams of the tyrants in the world." Inside, a banner burnishes his legacy: "This revolution is not known anywhere in the world without the name Khomeini."

Khamenei was a favorite pupil of Khomeini's from the early 1960s, but his tenure as supreme leader will never be lionized in the same way. Indeed, Khamenei has long labored in the shadow of more powerful figures, or alongside more flamboyant ones, starting with his own father.

Khamenei was born in the shrine city of Mashhad, burial place of Imam Reza, the eighth Shiite imam. For him, joining the clergy was expected.

"One of the fundamental experiences in his life was his relation with his father, [which] was very, very problematic, and I think made him lose his self-confidence," says Mehdi Khalaji, an Iran specialist at The Washington Institute for Near East Policy, who is writing a biography of Khamenei. "His father was aggressive [and] not communicative. [Khamenei] didn't want to become a cleric; he became a cleric. He wanted to leave Mashhad. He went to Qom – his father pressured him, so he didn't stay long. He went back. His father was against his political activities; his father was almost always against anything he has done."

One result, Mr. Khalaji suggests, is that Khamenei is "not able to make big decisions and take responsibility for them. He wants to have full authority without full responsibility, because he is afraid – he's not like Khomeini, who had no shame about making a decision and pronouncing it."

Khamenei's passion for literature began at an early age, when his mother would recite the poems of the Persian writer Hafez and tell him stories from the Quran. In Mashhad, Khamenei joined a literary association and hobnobbed with poets and writers. He kept up poetry readings when pursuing seminary studies in Qom and was later nicknamed the "poet president."

Iran's future leader also once had a love of music. By one account, in 1988 – when most forms of music were outlawed – he was asked by law students how they could tell which music was forbidden. He responded: "When in doubt ... listen to it."

Khamenei's time in prison, some three years in total, was another formative period in his life. In 1974 he shared that tiny cell, meant for one, with Houshang Asadi, a communist who came to be impressed with the solemn religiosity of his fellow inmate. Mr. Asadi respected Khamenei's humanity – at one point, they both hand-fed another prisoner for days – and his quick humor. Khamenei had a "sweet laugh" and was "always cheerful and up for a joke," recounts Asadi in his 2010 memoir, "Letters to My Torturer."

"He would recite the Quran quietly, he would pray, and then he would weep, sobbing loudly," writes Asadi. "He would lose himself completely to God. There was something about this type of spirituality that appealed to the heart."

Despite their different backgrounds, the two men formed a close bond. When they parted, Asadi recounts, he gave the thin and shivering Khamenei his sweater, and felt the "warm tears ... running down his face" as they embraced.

"Under an Islamic government, not a single tear would be shed by the innocent," Khamenei told him.

That was a promise that would not be kept, as Asadi discovered in 1983, when security forces loyal to Khomeini arrested him. Years of torture followed – the cruelty, as he described it, far worse than anything he had experienced under the shah. In fact, the thousands of political prisoners killed in the first decade of the Islamic revolution far outstripped the less than 100 recorded as dying in the shah's last decade.

In 1979, Khamenei became a Tehran Friday prayer leader and a deputy defense minister. His behind-the-scenes role in organizing Iran's military in the early days of the Iran-Iraq War led to an assassination attempt in 1981, when a tape recorder packed with explosives blew up during a press conference, paralyzing his right arm.

That blast – and another one two days later that killed 73 senior officials and would eventually pave the way for Khamenei's election as president – contributed to his wariness about personal security. In public, Khamenei wears a bulletproof vest beneath his clerical uniform and has bought a $7 million bombproof BMW, says Khalaji: "He's very sensitive about his security team; he actually manages these things himself – he is extremely paranoid about this sort of thing."

The vast carnage of the Iran-Iraq War of the 1980s – and the West's support for Saddam Hussein during it – added to Khamenei's conspiratorial distrust. Roughly 400,000 people died in the conflict.

While Iraqi forces used chemical weapons extensively, Tehran never unleashed them in return. Western chemical assistance to Baghdad and US intelligence help, including satellite imagery that made Iraqi chemical strikes more lethal, drove up Iran's death toll.

Many grievances have fueled the Islamic revolutionary chants of "Death to America!" over the years – starting with the 1953 coup, the first-ever conducted by the CIA, that reinstalled the detested shah. But US support in the 1980s for Iran's sworn enemy was seen as grievous proof of American perfidy.

"One real damaging episode was the [Iraqi] gas attacks on the Kurdish areas," says a veteran European diplomat. Even after it was clear that Iraq had carried out the atrocity, which killed 5,000 civilians, international reaction was mute to the first use of weapons of mass destruction since World War II. "This comes up over and over and over again," notes the diplomat.

For Khamenei, that confirmed the righteousness of Iran's revolution: "Remaining alive under [subjugation] to the rule of the superpowers is, in reality, death," he declared in 1980, "while [death] through cutting the bloody claws of the superpowers is life."

Throughout his two terms as president, Khamenei was often locked in political battle with Prime Minister Mir Hossein Mousavi – the man who would be a presidential candidate in 2009 and whose defeat sparked the opposition Green Movement and street protests. During the 1980s, disputes between the two men would be taken to Khomeini, who often ruled on the side of Mr. Mousavi.

Khamenei didn't distinguish himself as president and was only a mid-ranking cleric at the time. As journalist Elaine Sciolino reports in her book "Persian Mirrors," just months before Khomeini's death in 1989, Khamenei said: "I'm not qualified to be Supreme Leader. It's not the proper place for me."

In fact, history shows how reluctant Khamenei was to accept the role. Within hours of Khomeini's death, the Assembly of Experts met to choose a successor, to transfer God's authority from one mortal to the next. A videotape of the meeting, made public in 2008, reveals how one regime official conveyed stories about Khomeini's quiet support for Khamenei. The constitution had been changed in previous months to accommodate Khamenei's lesser theological credentials – he wasn't even an ayatollah, much less a top-flight "source of emulation" for Shiite followers. Still unconvinced was Khamenei himself, who stood up from his red leather seat in the chamber and took the podium, despite the chants of approval from other clerics. He stuttered, and finally said: "I'm against this, anyway."

Khamenei was shouted down, calls of "God is great!" went up, and the chairman concluded that "with this decision the hope of our enemies ... will be turned to hopelessness."

* * *

Two decades later, God's representative on earth took to another podium, this time to lead Friday prayers at Tehran University as Iran's Islamic regime faced its most serious crisis in a generation: the violent aftermath of the June 2009 presidential election.

Khamenei's turbulent tenure had turned his beard from black to white. As he stepped up to the lectern, he grasped the barrel of an AK-47 assault rifle – a tradition of Friday prayer leaders throughout the revolution.

It was one week after the vote that had reinstalled the populist firebrand Mahmoud Ahmadinejad for a second term as president. Khamenei had declared the result a "divine assessment," but millions of Iranians felt cheated, certain Mousavi had really won.

They took to the streets – as many as 3 million in Tehran in one day alone – carrying signs that read "Where is my vote?" Members of the ideological Basij militia cracked down on the protesters. More and more, Khamenei's portraits were torn down and torched amid chants of "Death to the dictator!"

Getting to that point had not been easy. When Khamenei was elevated to supreme leader in 1989, he was bestowed with Khomeini's title, but didn't inherit his charismatic magic – nor his theological gravitas. Throughout his career, higher-ranking clerics often took issue with his leadership, and its supposed "divine" status.

"In all his life, [Khamenei] was in the shadow of a greater authority, and that so bothered him," says biographer Khalaji. "When he was president, it was Khomeini, and when he became supreme leader, he [was not] recognized by the clergy [or by] the political elite of Iranian society – he was indebted to [many] other people."

When Khamenei favored the little-known Mr. Ahmadinejad, then mayor of Tehran, for president in 2005, he "thought that, finally, he had got rid of all those people who were bigger than him," says Khalaji. But Ahmadinejad was a hard-liner with little understanding of eco-nomics, who was seen by many as recklessly pushing Iran toward war with the US and Israel. Now, in 2009, his declared landslide victory had created an existential crisis, which Revolutionary Guard commanders would later admit took the regime "to the edge of a downfall."

Under pressure to ease the violence, Khamenei, at the prayer podium, didn't try to reassure the pro-democracy activists. Instead, he accused them of treason and being used by the "espionage machines working for Zionists and the Americans." He promised a fiercer crackdown.

Scores would die in the following months, as the regime crushed the opposition Green Movement. In Khamenei's worldview, the protests were no surprise. They were just the latest attempt by the US and European countries to back a nonviolent revolution like ones that had already been successful in Serbia, Georgia, Ukraine, and other nations. US officials had trumpeted their role in funding and training pro-democracy groups in those countries, which led directly to changes of government.

In Iran, "they saw that the United States is willing and able to instill regime change in other countries that they don't like, and does that openly," says the senior European diplomat. "This is perceived as an ongoing threat."

Back in 1995, the CIA had launched a $2 million campaign to beam anti-regime propaganda into Iran. Later that year, Congress appropriated $18 million to aid what then-House Speaker Newt Gingrich called an effort to “force the replacement of the current regime” in Tehran.

Within days, the Iranian parliament ear marked $20 million in counterespionage cash to counter this “secret” US effort. While those tit-for-tat moves garnered headlines, Khamenei took a more serious step at self-education. In 1997, he ordered a wide-ranging examination of case studies of the decline of dictatorships around the world.

From the People Power revolt in 1986 in the Philippines, to Czechoslovakia's Velvet Revolution in 1989, to political prisoner Nelson Mandela's rise in South Africa, Khamenei wanted to know how it all happened – and what tactical role Washington had played.

In 2000, Khamenei hinted at the project. "I have now reached the conclusion that the United States has devised a comprehensive plan to subvert the Islamic system," he said, believing it would be an "imitation" of the plan that led to the collapse of the Soviet Union. The focus on the Soviet Union might be expected, considering it has long been an academic interest of Khamenei.

Khamenei reads two to three books a week, according to Khalaji, and sleeps only three to four hours a night.

"Many of these books are on classical literature, the political history of Iran and the world. He is a serious student of the Soviet Union," he says. "But on the other hand, don't forget that [Khamenei] doesn't know the West at all. He has never traveled to the West; he is not interested even in the literature of the 20th century."

"Everything he knows about the West is from the perspective of the books of the Soviet Union," Khalaji adds. "So somehow his mind is shaped by that literature."

Still, Khamenei is provided a several-page news digest every day. He randomly watches television news channels, including BBC Persian, which Tehran officials have excoriated for seeking to undermine the regime.

A decade ago he learned to use the Internet and sometimes surfs the Web, says Khalaji. A believer in art and science, Khamenei has also embraced some superstitions like bibliomancy – seeking guidance by reading random passages, often in sacred texts. He has also made regular visits to the Jamkaran mosque, south of Tehran, seeking guidance from the "missing" 12th Imam Mahdi, the Shiite Messiah.

A far greater believer in the power of Jamkaran is Ahmadinejad, who last year boldly challenged Khamenei's diktat and lost – raising questions about Khamenei's "infallible" decision to back the divisive president in 2009.

"The hard-line [faction in] Iran has essentially tied its fortunes completely to Khamenei; it has said repeatedly that 'whatever [Khamenei] says is right,' " says analyst Farhi. "And what can you say against God's representative on earth, if he makes a decision?"

* * *

Crucial decisions are due on Iran's nuclear advances and US-Iran ties in the coming months that will test whether Khamenei's current mood is one of flexibility or hostility.

In US intelligence circles, the view has been that Khamenei isn't completely unpredictable, even if debate continues about the scale of his intransigence. The 2007 American National Intelligence Estimate on Iran found that the country made strategic moves based on a rational "cost-benefit analysis." By January this year, that assessment by all US intelligence agencies had not changed.

The result of Mr. Obama's overtures to Iran in early 2009 provide a useful example. Determined to change the US tone toward Iran, Obama said one week after his inauguration: "If countries like Iran are willing to unclench their fist, they will find an extended hand from us." Later, Obama marked the Persian New Year, calling for a "new beginning" with Iran.

Khamenei, with uncharacteristic speed, replied the next day in a speech. He cataloged decades of Iranian grievances and said Obama had "insulted Iran" from his first days in office. If the US offer was an "iron hand covered with the velvet glove," it would not do. Yet Khamenei promised: "You change, and we will also change our behavior, too."

Since then, Iran's 2009 election crisis has complicated the dynamic. So have a host of other factors – the covert US war, the Stuxnet computer virus, the crippling sanctions, and the recent US removal from its terrorist list of the Mojahedin-e Khalq (MEK/MKO), a cultlike group that opposes Iran's regime and has been linked to the assassinations of scientists in Tehran. So far this year, three rounds of high-level nuclear talks between Iran and nuclear powers have produced little progress.

"[Khamenei's] mind-set is that under threat and pressure, to show flexibility or compromise would be seen as a weakness," says Mr. Mousavian, the former member of Iran's national security council. "Therefore under such conditions, he consolidates and hardens his position. This is critical in understanding the position of Iran on nuclear negotiations."

Khamenei's reaction to any attack by Israel or the US on Iran's nuclear facilities would likely be even more truculent. The concept of "resistance" has been fundamental to the Islamic revolution since its inception in 1979, enabling Iran, its leaders say, to finally reverse 200 years of "shameful weakness" at the hands of Russian, British, and US colonial powers.

At least until a few years ago – before the US and Israel stepped up their covert war against Iran – senior Iranian officials boasted that they had never allowed a single overt or clandestine attack against Iran to go unavenged.

Iran’s “successful experience in resistance against the bullying and comprehensive pressures by America” were evidence of nothing less than God’s blessing on the Islamic Republic, Khamenei said this summer: “We have with our own eyes repeatedly witnessed divine assistance in these challenges.”

Khamenei views the result of any new war, therefore, as inevitable. “In the confrontation between truth and falsehood, and between the camp of God and the camp of Satan,” he says, the Quran teaches that victory belongs to Muslim believers, “to anybody who fights for a divine cause” – even if they can’t match the enemy’s “power, wealth, and weapons.”

That unbending right-is-might belief will dictate the severity of Iran’s response to military action. The list of Iran's likely moves are well known to analysts and would ensure conflict for years to come. Inside the country, the Islamic republic would almost certainly kick out UN nuclear inspectors and decide to push all-out for a nuclear weapon – with Khamenei calculating that no other step could deter future attack or preserve the Islamic regime.

Outside the country, Iran would strike hard with proven asymmetric capabilities. Iranian commanders have long trumpeted their ability to "defend" Iran, noting that dozens of American military bases and all of Israel are within its missile range. Iran has warned it would mine and close the Strait of Hormuz, through which a significant portion of global oil supplies flow, while it attacked US warships in the Persian Gulf with fast-boat swarming tactics.

Iran could ask the proxy allies it arms and supports on the front line with Israel – Hezbollah in Lebanon, and Hamas in Gaza – to unleash its missile arsenals. The recent eight-day Gaza fight illustrated what could be achieved, in Khamenei's view. Revolutionary Guard chiefs said they were "proud" that Iran had provided Hamas with the know-how to build its Fajr-5 missiles, which shook Israel by bringing Tel Aviv and Jerusalem into range for the first time.

Get the Monitor Stories you care about delivered to your inbox. By signing up, you agree to our Privacy Policy

Khamenei hailed the "victorious resistance" of the people of Gaza, slotting the event into his ever-triumphant worldview. It was a lesson, Iran's supreme leader said, "that resistance is the only way to defeat the enemies of Islam."

• Scott Peterson is the author of "Let the Swords Encircle Me: Iran – A Journey Behind the Headlines," for which some of the reporting in Tehran was first conducted. Follow him on Twitter: @peterson_scott