이 문서에서는 폼 인증 쿠키 데이터의 암호화, 해독, 유효성 검사에 사용할 키를 만드는 방법을 설명합니다. 이 문서에서 만든 키를 Machine.config 파일의<system.web>요소에 있는 <machineKey> 섹션의validationKey및decryptionKey특성에 사용할 수 있습니다.
코드는 난수 생성기를 사용하여 명령줄 인수에 따라 임의의 수의 바이트를 만듭니다. 임의의 바이트를 만든 후에는 .config 파일에서 사용하기에 적절한 16진수 문자열로 바이트의 서식이 지정됩니다.
참고명령줄에서 전달되는 값 크기의 두배에 해당하는 16진수 문자열이 만들어집니다. 예를 들어, 키에 24바이트를 지정하면 변환 후 만들어진 문자열 길이는 48바이트가 됩니다.decryptionKey의 유효한 값은 8 또는 24입니다. 이것은 각각 DES(데이터 암호화 표준)에 대해 16바이트 키를 만들거나 삼중 DES에 대해 48바이트 키를 만듭니다.validationKey의 유효한 값은 20-64입니다. 이것은 40-128바이트 길이의 키를 만듭니다. 코드의 출력은 Machine.config 파일로 복사하여 붙여넣을 수 있는<machineKey>요소 전체입니다.
다음 코드를 .cs 파일에 추가합니다.
using System;using System.Text;using System.Security.Cryptography;namespace Crypto{ public class KeyCreator { public static void Main(String[] args) { String[] commandLineArgs = System.Environment.GetCommandLineArgs(); string decryptionKey = CreateKey(System.Convert.ToInt32(commandLineArgs[1])); string validationKey = CreateKey(System.Convert.ToInt32(commandLineArgs[2])); Console.WriteLine("<machineKey validationKey=\"{0}\" decryptionKey=\"{1}\" validation=\"SHA1\"/>", validationKey, decryptionKey); } static String CreateKey(int numBytes) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[numBytes]; rng.GetBytes(buff); return BytesToHexString(buff); } static String BytesToHexString(byte[] bytes) { StringBuilder hexString = new StringBuilder(64); for (int counter = 0; counter < bytes.Length; counter++) { hexString.Append(String.Format("{0:X2}", bytes[counter])); } return hexString.ToString(); } }}
해독 키와 유효성 검사 키의 크기에 해당하는 두 개의 정수 값을 전달하여 명령 프롬프트에서 응용 프로그램을 실행합니다. 예를 들어, 콘솔 응용 프로그램에 HashConfigCs.exe라는 이름을 지정한 경우에는 응용 프로그램의 Bin\debug 디렉터리의 명령줄에서 다음 구문을 입력합니다.