Resolution for failed to use the provider "rsaprotectedconfigurationprovider" for decryption

Source: Internet
Author: User

UnavailableProgramSolution to "rsaprotectedconfigurationprovider": How to Use the cryptography Application Block of Enterprise Library 3.0 to process Encryption
This article does not demonstrate how to use the configuration tool to encrypt the configuration area, nor how to export and import key files, but mainly solves two problems:
1. after the configuration area is encrypted using the configuration tool, (generally, configprotectionprovider has two options: rsaprotectedconfigurationprovider and dataprotectionconfigurationprovider.) The configuration is normal on the local machine, but if it is switched to another machine, the Configuration tool cannot be used. When rsaprotectedconfigurationprovider is used, the following error is reported: The provider "rsaprotectedconfigurationprovider" cannot be used to decrypt the rule.

2. After using the encryption processing block of the cryptography application block, we create an encryption Ric providers and useAlgorithmIn this process, a key file is generated. However, other machines that copy the key file are invalid (the reason is explained later ). Of course, we can import the key file on another machine by exporting the key from the local machine. However, this only solves the problem of using the same key file between developers. It is not applicable to deployment to the client. Because it is unlikely that we will install Enterprise Library 3.0 on the client, or manually configure this key after installing the program. (This significantly increases the complexity of the installer, And the installer may not be a professional .)

first, we declare that it is not feasible to use relative paths in protectedkeyfilename! Why? Because the key file cannot be directly copied to another machine. When we configure the key file on each machine (including creating a new key or importing a key, we need to save the absolute path of the Key), we already know the absolute path, so there is no need to use the relative path! David Hayden said in a response to a netizen's question about why relative paths are not used: I wocould have thought that relative paths wouldbe fine, but I pulled this from the documentation within the sectionmanaging and distributing keys which is pretty specific about the needfor absolute paths .... the cryptography Application Block stores eachkey in a separate file on the local computer .... he said: Although I thought the relative path would be clever (but not actually ), but I removed it from the "manage and distribute key files" section of the document. In this section, it is quite clear that the absolute path... encryption application block needs to be used to store a separate file for each key file on the local computer. (See http://www.codeplex.com/entlib/Thread/View.aspx? Threadid = 9834)

Since the key files are related to the local computer, the relative path is of little significance (I dare not say it is meaningless ). the key file cannot be directly copied to another machine because it is encrypted using dpapi (Windows data protection. Data encrypted using dpapi can only be used on a specific computer. Changing a machine will certainly not work! Because you used the information of the current computer and the user logging on to the computer during encryption.

So by the way: there is a selection item in the process of generating key files. One is the user mode and the other is the machine mode. User mode is used to log on to the computer.
Only users can use this key file. In the machine mode, users on this computer can use this key file. For example, deploy webforms
The website must use the machine mode. For winforms deployment, if you cannot confirm that only one account on the computer will use the software you deployed, use the machine mode.
!

Solution to the first problem:

If you want to encrypt a configuration file (such as Web. config and App. config) on one computer and use it on other computers, this will achieve our goal.

When it comes to configuration file encryption, we naturally need to mention two of them:

Dpapiprotectedconfigurationprovider. Use Windows Data Protection API (dpapi) to encrypt and decrypt data.

Rsaprotectedconfigurationprovider. Use the RSA encryption algorithm to encrypt and decrypt data.

Both providers provide strong data encryption. However, if you plan to use the same encrypted configuration file on multiple computers, you only need to use rsaprotectedconfigurationprovider. This allows you to export the encryption keys used to encrypt data and import them to another computer.

When you use the configuration tool to encrypt the configuration area of the configuration file, you can specify the protectedconfigurationprovider. Obviously, we can only use rsaprotectedconfigurationprovider to solve this problem. Because the RSA key containers on different computers are different, we need to export an RSA key container from one computer and then import it to another computer! Because the import method can be implemented using DOS commands, there is no problem in deployment! In addition, because. netframework has a default RSA key container named "netframeworkconfigurationkey", this default parameter is displayed in the machine. config file.

The following message is displayed: aspnet_regiis.exe is under c: \ windows \ Microsoft. NET \ framework \ v2.0.50727. Drive C is my installation path. Therefore, pay attention to the path when using the doscommand. (You can choose Start> All Programs> Microsoft Visual Studio 2005> Visual Studio Tools> Visual Studio 2005 to open the CMD interface using the aspnet_regiis command .)

The procedure is as follows:

(1) Export the RSA key container on the current computer. (You can specify the path before exporting the file .)

Aspnet_regiis-Px "netframeworkconfigurationkey" D: \ rsakeys. XML-pri

(2) encrypt the configuration file with the enterprise database tool on the current computer. Protectedconfigurationprovider can only be selected

Rsaprotectedconfigurationprovider.

(3) import the RSA key container named "netframeworkconfigurationkey" to the deployed computer.

Aspnet_regiis-pi "netframeworkconfigurationkey" D: \ rsakeys. xml

(1) and (2) can be operated directly on the current computer, and (3) DOS commands can be completed by the program during deployment.

This is done!

Tip: it is possible that step (1) fails to export. It cannot use the-pri parameter, which is the information used for export and decryption! Without it, you can only encrypt new things on other machines. The solution is as follows:

(1) On the current computer, create a new RSA key container named customkeys. (Here there is a user-level and computer-level. The following method is to create a computer-level name according to your requirements)

Aspnet_regiis-PC "customkeys"-exp

(2) grant access permissions to the account on the current computer

Aspnet_regiis-pa "customkeys" "nt authority \ Network Service"

Other accounts that require access permissions should also be authorized.

(3) export the RSA key container on the current computer. (You can specify the path before exporting the file .)

Aspnet_regiis-Px "customkeys" D: \ rsakeys. XML-pri

(4) On the current computer. config (in c: \ windows \ Microsoft. in net \ framework \ v2.0.50727 \ config), replace keycontainername = "netframeworkconfigurationkey" with the newly created name: keycontainername = "customkeys ".

(5) use the enterprise database tool to encrypt the configuration file on the current computer. Protectedconfigurationprovider can only select rsaprotectedconfigurationprovider.

(6) import the RSA key container named "netframeworkconfigurationkey" to the deployed computer.

Aspnet_regiis-pi "netframeworkconfigurationkey" D: \ rsakeys. xml

By the way, the command to delete the RSA key container is as follows:

Aspnet_regiis-PZ "customkeys"

When you enter an incorrect command, the Help Command information is displayed. Note: If the preceding command is copied, check the underline and space!

Two solutions are proposed for the second problem:

Solution 1:

As mentioned above, you can use the method to export the key file first and then import the key file to solve this problem. This solution only addresses the needs of developers, but does not meet the actual needs of our deployment! Of course, if you are willing to install enterprise library3.0 on the deployed machine and use it to reconfigure the encrypted file, it is very easy. The following is a solution that meets the actual deployment requirements.

Enterprise Library 3.0 can import the key file on the deployed machine manually. This also means that the key file can be imported to the deployed machine through programming. Because manual import must also be implemented through a program.

So, this partCodeWhere can I find it? Enterprise library3.0 is not providedSource codeAnd the source code of the Configuration tool. In the enterpriselibrary solution file under the c: \ entlib3src \ app blocks directory (my installation directory), we can find some clues from it.

Here, we will deploy the key file only for javasriccryptoproviders!

1. The steps for deploying the new key file are as follows:

(1) create a new key file.

 

// -- Generate a new key file
Byte [] Key = keymanager. generatesyuncrickey (typeof (descryptoserviceprovider ));
Byte [] encryptedkey = protecteddata. Protect (Key, null, dataprotectionscope. currentuser );
Stream FS = NULL;
Try
{
FS = new filestream (keyfilepath, filemode. Create );
Keymanager. Write (FS, encryptedkey, dataprotectionscope. currentuser );
FS. Flush ();
}
Finally
{
If (FS! = NULL)
FS. Close ();
}
(2) modify the path of the key file in the configuration file. Is the protectedkeyfilename attribute.

 

/** // <Summary>
/// Modify the Key Path in the configuration file, that is, the attribute value of protectedkeyfilename
/// </Summary>
/// <Param name = "keyfilepath"> path of the custom key file </param>
Private void modifprotectedkeyfilename (string keyfilepath)
{
// Read from the group Node
Configuration Config = configurationmanager. openexeconfiguration (configurationuserlevel. None );
If (config. hasfile)
{
Configurationsection = config. Sections ["securitycryptographyconfiguration"];
Cryptographysettings = configurationsection as cryptographysettings;
Nametypeconfigurationelementcollection <your ricproviderdata, custom?riccryptoproviderdata> elementcollection = cryptographysettings. Your riccryptoproviders;
Repeated ricproviderdata into ricproviderdata = elementcollection. Get ("descryptoserviceprovider ");
Using ricproviderdata. elementinformation. properties ["protectedkeyfilename"]. value = keyfilepath;
Config. Save (configurationsavemode. Minimal );
}
}

However, someone may ask, can the exported key file restore the key file during development? Although creating a new key file can solve the deployment problem, I want to use programming methods to restore the key file during development, such as me. Because before deployment, I already had some data encrypted with this key! Of course, you can put the data in the deployment and then initialize the encryption! :) Joke! I just want to broaden my mind! Enter the subject:

2. Follow these steps to restore the key file:

(1) restore the key file.

// -- Restore the key file
Stream FS = NULL;
// Distribution key file name: exportkey.txt, password: 123456
Using (Stream fileout = file. openread ("exportkey.txt "))
{
Protectedkey = keymanager. restorekey (fileout, "123456", dataprotectionscope. localmachine );
Try
{
FS = new filestream (keyfilepath, filemode. Create );
Keymanager. Write (FS, protectedkey. encryptedkey, dataprotectionscope. currentuser );
FS. Flush ();
}
Finally
{
If (FS! = NULL)
FS. Close ();
}
}
(2) modify the path of the key file in the configuration file. Is the protectedkeyfilename attribute.

This is the same as in (1!

To sum up the solution, the idea is simple: Create a new or restore key file so that the key file is associated with the deployed machine, and then modify the path of the key file in the configuration file.

Let's talk about the second solution now!

Solution 2:

Initially, there may be an idea that it would be much easier to generate a key file and copy it directly to any computer. Below, I will provide this solution.

The idea is: place the randomly generated key in the XML file, and then add the XML file to the Assembly by embedding it, then we can read the key from the XML file through reflection in a general encryption and decryption class, and then use it for encryption and decryption. In addition, we can encrypt and decrypt keys stored in XML files in a general reversible encryption method. However, it is emphasized that this method is not as secure as above. After all, keys placed in XML files may be cracked. Of course, this method can still be used in systems with low security requirements.

// Configure //-----------------------------------------------------------------------------------------
// Module ID:
// File name: customcryptography. CS
// Description: mcryptography data symmetric encryption and decryption class
// Author: chenjie
// Written on: 2007-5-30
// Copy 2007
// Configure //-----------------------------------------------------------------------------------------
Using system;
Using system. text;
Using system. reflection;
Using system. IO;
Using system. xml;
Using system. Security. cryptography;

Namespace cryptographylib
{
/** // <Summary>
/// Custom Data symmetric encryption and decryption class
/// </Summary>
Public class customcryptography: icryptography
{
Private constant # region private constant
/** // <Summary>
/// Embed the XML file into the project assembly
/// </Summary>
Private const string key_file = "cryptographylib. systemkey. config ";
# Endregion

Method of implementing the interface # region method of implementing the interface

/** // <Summary>
/// Encrypted string
/// </Summary>
/// <Param name = "plaintext"> plaintext </param>
/// <Returns> ciphertext </returns>
Public String encryptdata (string plaintext)
{
String encryptdata = string. empty;
// Create a new des key.
Descryptoserviceprovider key = new descryptoserviceprovider ();
// Set the secret key of the Data Encryption Standard (DES) algorithm and the value of the initialization vector of the symmetric algorithm
Byte [] Key = NULL;
Byte [] IV = NULL;
Getkeyandiv (Out Key, out IV );
Key. Key = key;
Key. IV = IV;
Return encryptdata (plaintext, key );
}

/** // <Summary>
/// Decrypt the string through descryptoserviceprovider
/// </Summary>
/// <Param name = "decryptedtext"> ciphertext </param>
/// <Returns> plaintext </returns>
Public String decryptdata (string decryptedtext)
{
String decryptdata = string. empty;
// Create a new des key.
Descryptoserviceprovider key = new descryptoserviceprovider ();
// Set the secret key of the Data Encryption Standard (DES) algorithm and the value of the initialization vector of the symmetric algorithm
Byte [] Key = NULL;
Byte [] IV = NULL;
Getkeyandiv (Out Key, out IV );
Key. Key = key;
Key. IV = IV;
Return decryptdata (decryptedtext, key );
}

/** // <Summary>
/// Use MD5 to encrypt the string
/// </Summary>
/// <Param name = "plaintext"> plaintext </param>
/// <Returns> ciphertext </returns>
Public String encryptdatabyhash (string plaintext)
{
Hashalgorithm hashcryptoservice = new sha1managed ();
Byte [] bytin = utf8encoding. utf8.getbytes (plaintext );
Byte [] bytout = hashcryptoservice. computehash (bytin );
Return convert. tobase64string (bytout );
}

/** // <Summary>
/// Compare the MD5 encrypted string
/// </Summary>
/// <Param name = "plaintext"> plaintext </param>
/// <Param name = "hashedtext"> hash value to be compared </param>
/// <Returns> whether the returns are the same. If yes, true is returned. Otherwise, false is returned. </returns>
Public bool comparehash (string plaintext, string hashedtext)
{
Bool compare = false;
String encryptdata = encryptdatabyhash (plaintext );
Compare = encryptdata. Equals (hashedtext );
Return compare;
}

# Endregion

Private method # region private Method
/** // <Summary>
/// Encrypted string
/// </Summary>
/// <Param name = "plaintext"> plaintext </param>
/// <Param name = "key"> abstract base class of symmetric algorithms </param>
/// <Returns> ciphertext </returns>
Private string encryptdata (string plaintext, symmetricalgorithm key)
{
String encryptdata = string. empty;
Byte [] plaintextbytes = encoding. utf8.getbytes (plaintext );

/** // ---------- Method 1 ----------------------------
//// Create a memorystream object
// Memorystream MS = new memorystream ();
/** // Create an encrypted stream
// Cryptostream encstream = new cryptostream (MS, key. createencryptor (), cryptostreammode. Write );
/** // Create a streamwriter object
// Streamwriter Sw = new streamwriter (encstream );
// Sw. writeline (plaintext );
// Sw. Close ();
// Encryptdata = convert. tobase64string (Ms. toarray ());
// Ms. Close ();
/** // ---------- Method 1 ends ----------------------------

// ---------- method 2 ----------------------------
memorystream MS = new memorystream ();
cryptostream cs = new cryptostream (MS, key. createencryptor (), cryptostreammode. write);
CS. write (plaintextbytes, 0, plaintextbytes. length);
CS. flushfinalblock ();
encryptdata = convert. tobase64string (Ms. toarray ();
// ---------- method 2 ends ----------------------------

// clear the content in the array
array. Clear (plaintextbytes, 0, plaintextbytes. Length);
return encryptdata;
}

/** //


// decrypt the string
//
// ciphertext
// abstract base class of symmetric algorithms
/// plaintext
private string decryptdata (string decryptedtext, symmetricalgorithm key)
{< br> string decryptdata = string. empty;
byte [] decryptedbytearray = convert. frombase64string (decryptedtext);

/** // ---------- Method 1 ----------------------------
//// Create a memorystream object for the decryption string
/Memorystream MS = new memorystream (decryptedbytearray );
/** // Create a cryptostream object
// Cryptostream encstream = new cryptostream (MS, key. createdecryptor (), cryptostreammode. Read );
/** // Create a streamreader object
// Streamreader sr = new streamreader (encstream );
// Decryptdata = Sr. Readline ();
// Sr. Close ();
// Encstream. Close ();
// Ms. Close ();
/** // ---------- Method 1 ends ----------------------------

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.