Generate Machine Key Elements for Web Farm

The <machineKey> Element configures keys to use for encryption and decryption of forms authentication cookie data and viewstate data, and for verification of out-of-process session state identification. This section can be declared at the machine, site, and application levels, but not at the subdirectory level. For anybody that's running ASP.NET on a server farm, the <machineKey> element is one of those guys you want to know as much as you can about IN ADVANCE - before you run into problems!

 

 

Here is an example Configuration Structure for the element:

<configuration>
<system.web>
<machineKey><machineKey validationKey="AutoGenerate|value[,IsolateApps]"
decryptionKey="AutoGenerate|value[,IsolateApps]
validation="SHA1|MD5|3DES"/>


The validationKey attribute specifies the key used for validation of encrypted data. validationKey is used when enableViewStateMAC is true to create a message authentication code (MAC) to ensure that view state has not been tampered with. ValidationKey is also used to generate out-of-process, application-specific session IDs to ensure that session state variables are isolated between sessions.

AutoGenerate specifies that ASP.NET generates a random key and stores it in the Local Security Authority (LSA). The AutoGenerate option is the default value, but you definitely DON'T want this for a web farm! If you add the IsolateApps modifier to the validationKey value, ASP.NET generates a unique encrypted key for each application using each application's application ID. For a web farm, you want to manually put in your own keys and make sure they are EXACTLY THE SAME on each machine in the farm.

The value attribute specifies a manually assigned validation key. This value must be manually set to ensure consistent configuration across a network of Web servers (a Web farm). The key must be a minimum of 40 characters (20 bytes) and a maximum of 128 characters (64 bytes) long. If keys shorter than the maximum length are used, they should be created by a truly random means, such as by using RNGCryptoServiceProvider, which we will show below. The recommended key length is 128 hexadecimal characters. If you add the IsolateApps modifier to the validationKey value, ASP.NET generates a unique encrypted key for each application using each application's application ID.


The decryptionKey attribute specifies the key used to encrypt data. decryptionKey is used for Forms authentication encryption and decryption and for view state encryption when validation is 3DES.


The AutoGenerate attribute for decryptionKey specifies that ASP.NET generates a random key and stores it in the LSA. The AutoGenerate option is the default value. If you add the IsolateApps modifier to the decryptionKey value, ASP.NET generates a unique encrypted key for each application using each application's application ID.


The value attribute for decryptionKey specifies a manually assigned key. This value must be manually set to a string of hexadecimal characters to ensure consistent configuration across a Web farm. The key should be 16 characters in length when using DES encryption and 48 characters in length when using Triple DES encryption. If keys shorter than the maximum length are used, they should be created by a truly random means. ASP.NET can use Triple DES only on computers on which 128-bit encryption is available. If you add the IsolateApps modifier to the decryptionKey value, ASP.NET generates a unique encrypted key for each application using each application's application ID.


validation specifies the type of encryption used for validation of data:

  • SHA1 specifies that ASP.NET uses SHA1 encryption.
  • MD5 specifies that ASP.NET uses MD5 encryption.
  • 3DES specifies that ASP.NET uses Triple-DES (3DES) encryption. When 3DES is specified, forms authentication defaults to SHA1. When the validation attribute is set to 3DES, the view state validation technique uses 3DES encryption.

In order to use the above as a programming exercise to provide something useful, I've created a WebForm that creates the entire <machineKey> element so that you can copy it to the clipboard and paste it into the machine.config (or other config) file of each server on your farm. Yay! No more corrupted viewState and other nasty messages that you couldn't figure out until you were lucky enough to land on this page! Enjoy.




The WebForm1.Aspx fle:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
Inherits="GenerateMachineKey.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
<script>
function clipCopy(strElem){
strElem.focus();
strElem.select();
window.clipboardData.setData('Text', strElem.value);
}

</script>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 24px;
POSITION: absolute; TOP: 176px" runat="server"
Width="784px" Height="88px" TextMode="MultiLine"></asp:TextBox>
<asp:Label id="Label1" style="Z-INDEX: 102; LEFT: 288px;
POSITION: absolute; TOP: 56px" runat="server"
Width="328px" Height="48px" Font-Names="Comic Sans MS"
Font-Size="Larger">Pete's Nifty Machine Key Generator</asp:Label>
<asp:Button id="Button1" style="Z-INDEX: 103; LEFT: 192px;
POSITION: absolute; TOP: 280px" runat="server"
Width="208px" Text="Generate Me A Key!"></asp:Button>
<INPUT style="Z-INDEX: 104; LEFT: 448px; WIDTH: 200px;
POSITION: absolute; TOP: 280px; HEIGHT: 24px"
type="button" value="Copy to Clipboard" οnclick="clipCopy(TextBox1);">
</form>
</body>
</HTML>
'

The Webform1.aspx.cs File:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.IO;
using System.Text;


namespace GenerateMachineKey
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{

}
// generates a random <machineKey> element that you can use
// to replace the existing one in your machine.config file
// useful for synchronization of the ASP.NET encryption and
// validation keys in your web farm


static RNGCryptoServiceProvider srng = new RNGCryptoServiceProvider();

// 64 bytes is max size supported by ASP.NET
const int validationKeyLength = 64;
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Button Button1;

// 24 bytes is max size supported by ASP.NET (3DES)
const int decryptionKeyLength = 24;

static string GenerateKey(){

StringBuilder sb = new StringBuilder();
sb.Append("<machineKey validationKey='");

sb.Append( writeKeyAsHexDigits(getRandom(validationKeyLength)));

sb.Append("'");
sb.Append(" decryptionKey='");

sb.Append(writeKeyAsHexDigits(getRandom(decryptionKeyLength)));

sb.Append("'");
sb.Append(" validation='SHA1'/>");
return sb.ToString();
}
static byte[] getRandom(int cb)
{
byte[] randomData = new byte[cb];
srng.GetBytes(randomData);
return randomData;
}
static string writeKeyAsHexDigits(byte[] key)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < key.Length; ++i)
{

sb.Append( String.Format("{0:X2}", key[i]));

}
return sb.ToString();
}



#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void Button1_Click(object sender, System.EventArgs e)
{
TextBox1.Text =GenerateKey();

}
}
}
And true to form, if you are just too lazy to download and play with the code and you want to try it out online, I just happen to have my free GenerateMachineKey page working right over here. The Visual Studio.NET 2003 solution zip file can be downloaded below (if you don't have VS.NET 2003, just start an empty web project and add the files to it).

转载于:https://www.cnblogs.com/weishuai/archive/2011/01/28/1947231.html

### 回答1: `RSA_generate_key_ex` 是 OpenSSL 库中用于生成 RSA 密钥对的函数。它可以指定 RSA 密钥长度、公钥指数以及随机数生成函数等参数,生成一个 RSA 公私钥对,适用于加密、签名等场景。 ### 回答2: RSA是一种经典的非对称加密算法,它的安全性基于大数分解的难度。RSA非常适合用于保护对称加密算法的密钥传输、数字签名和任意消息的加密。在OpenSSL库中,可以使用函数rsa_generate_key_ex生成RSA公私钥对。下面详细分析这个函数。 函数定义: RSA *rsa_generate_key_ex(int bits, BIGNUM *e, void (*callback)(int,int,void *), void *cb_arg); 函数参数: bits:密钥长度,单位为比特数。一般选用1024、2048、4096等,长度越大加密强度越高,但计算时间越长。 e:用于RSA模数N的指数。常用的取值为65537(0x10001),因为它的二进制形式只有两个1,计算速度较快。 callback:提供一个回调函数,用于显示密钥生成进度或者打印错误信息。可以为NULL,表示不需要回调。 cb_arg:回调函数的参数,可以为NULL。 函数返回值: 成功则返回生成的RSA公私钥对,失败则返回NULL。 函数实现: 函数rsa_generate_key_ex的实现比较复杂,主要包括下面的步骤: 1.检查参数:检查bits、e和callback是否符合要求,如果不符合则返回NULL。 2.生成RSA密钥素数p和q:调用函数BN_generate_prime_ex,该函数使用Miller-Rabin算法和Lucas-Lehmer算法生成素数,保证生成的素数长度为bits/2,同时进行多次重复测试。 3.计算N和phi(N):计算RSA模数N和欧拉函数phi(N),这两个值都是大素数p和q的乘积。phi(N)表示小于N的正整数与N互质的个数。 4.计算e的模反元素d:根据RSA加密的数学原理,e和d两个数必须满足下面的条件:e*d &equiv; 1 (mod phi(N)),即e和d互为模phi(N)意义下的乘法逆元素。可以使用扩展欧几里得算法计算d。 5.生成RSA公私钥对:根据上面生成的数据,生成RSA公私钥对。公钥包括模数N和指数e,私钥包括模数N和指数d。 6.调用回调函数:如果回调函数不为NULL,执行回调函数并传入进度参数。 7.返回结果:返回生成的RSA公私钥对,或者返回NULL。 总结: 函数rsa_generate_key_ex是OpenSSL库中生成RSA公私钥对的核心函数之一,它可以方便地调用库中的素数生成和模反元素计算等功能,生成的RSA密钥可以用于加密、解密、数字签名等各种安全应用。但是,需要注意选择合适的密钥长度和指数,以保证算法的安全性和性能。同时,建议使用回调函数来显示密钥生成进度和错误信息,以便进行调试和维护。 ### 回答3: RSA算法是一种用于加密和解密的非对称加密算法,具有高强度的数据安全保障能力。而在RSA算法中,密钥生成一直是重要的步骤之一,其中rsa_generate_key_ex()函数就是用来生成RSA密钥的函数。 rsa_generate_key_ex()函数是一个RSA密钥对生成函数,它可以在输入的参数中指定算法、长度、随机因子等参数,来生成一对RSA公钥和私钥。 函数结构: int rsa_generate_key_ex(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); 函数参数: rsa:输入参数,表示RSA密钥对结构体; bits:输入参数,表示密钥位数,一般情况下,RSA算法要求密钥至少为2048位; e:输入参数,表示密钥指数,一般情况下,指数取65537; cb:输入参数,表示回调函数,可为NULL。 函数返回值: 成功,返回1;失败,返回0。 rsa_generate_key_ex()函数中,参数bits表示RSA密钥位数,一般来说,这个值越大,安全性也就越高,但同时密钥的计算和处理效率也会降低。一般情况下,RSA算法要求密钥至少为2048位。 参数e表示密钥指数,一般来说,RSA加密算法采用常数65537作为指数,这是因为65537是一个较大的素数,且只有两个位上是1,因此选用65537作为指数可以加快加密和解密的速度。 参数cb表示回调函数,可用于跟踪密钥生成的过程,以及在密钥生成的过程中进行参数的自定义。 总之,rsa_generate_key_ex()函数是一个强大的RSA密钥对生成函数,可用于创建RSA公钥和私钥。函数使用简单,只需要适当设置参数,即可快速生成RSA密钥,为数据安全保障做出应有的贡献。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值