I was using the Cryptography portion Enterprise Library 3.1 for the encryption and decryption of data in my Windows application.  Part of the configuration process creates a key file (*.key) necessary for the encryption/decryption to work.

 It was all working fine until I tried to publish and deploy the application. The cryptography piece would not work when the application was deployed to another machine. Here is why. The algorithm that builds the key file uses local machine information to build the key.  When the key file is placed on another machine, the machine information is different; consequently the cryptography fails with the following error message: "Key not valid for use in specified state. \r\n" Source="System.Security" 

 How do you fix this problem?

 

1)      Create a password protected text version of the key file (for example, AppKey.txt). Use the Enterprise Library Application Configuration tool to create a text version of the key file (for example, AppKey.txt).

2)      When deploying your application, make sure you deploy the text version of your key file (AppKey.txt) and not the key file (AppKey.key).

3)      In your application, at start-up, add the following code I found on codeplex (see DevLingo entry July 17, 2007).  The code reads the text file (AppKey.txt) and recreates the key file (AppKey.key).  It then updates the app.config file, to point to the location of the new AppKey.key file.