The System.Security.Cryptography namespace includes the RNGCryptoServiceProvider class that you can use to generate this string, as demonstrated in the following GenerateCryptoKey.aspx sample:
<%@ Page Language="c#" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<HTML>
<body>
<form runat="server">
<H3>Generate Random Crypto Key</H3>
<P>
<asp:RadioButtonList id="RadioButtonList1"
runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="40">40-byte</asp:ListItem>
<asp:ListItem Value="128" Selected="True">128-byte</asp:ListItem>
</asp:RadioButtonList>
<asp:Button id="Button1" runat="server" onclick="GenerateKey"
Text="Generate Key">
</asp:Button></P>
<P>
<asp:TextBox id="TextBox1" runat="server" TextMode="MultiLine"
Rows="10" Columns="70" BackColor="#EEEEEE" EnableViewState="False">
Copy and paste generated results</asp:TextBox></P>
</form>
</body>
</HTML>
<script runat=server>
void GenerateKey(object sender, System.EventArgs e)
{
int keylength = Int32.Parse(RadioButtonList1.SelectedItem.Value);
// Put user code to initialize the page here
byte[] buff = new Byte[keylength/2];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// The array is now filled with cryptographically strong random bytes
rng.GetBytes(buff);
StringBuilder sb = new StringBuilder(keylength);
int i;
for (i = 0; i < buff.Length; i++) {
sb.Append(String.Format("{0:X2}",buff[i]));
}
// paste to the textbox to the user can copy it out
TextBox1.Text = sb.ToString();
}
</script>
Summary
ASP.NET ViewState is a new kind of state service that developers can use to track UI state on a per-user basis. There''''s nothing magical about it. It simply takes an old Web programming trick—roundtripping state in a hidden form field—and bakes it right into the page-processing framework. But the result is pretty wonderful—a lot less code to write and maintain in your Web-based forms.
You won''''t always need it, but when you do, I think you''''ll find ViewState is a satisfying addition to the feast of new features ASP.NET offers to page developers.
Susan Warren is a program manager for ASP.NET on the .NET Framework team.