문제

여기에 AES 방법을 사용하고 있습니다. http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx

바이트 배열로 변환하여 AES 암호화 방법으로 전달하는 문자열 값을 원합니다. 방법이 예상하는 올바른 바이트 배열 크기를 생성하기 위해 문자열이 몇 개의 문자가되어야합니까?

static byte[] encryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");

        // Declare the stream used to encrypt to an in memory
        // array of bytes.
        MemoryStream msEncrypt = null;

        // Declare the RijndaelManaged object
        // used to encrypt the data.
        RijndaelManaged aesAlg = null;

        try
        {
            // Create a RijndaelManaged object
            // with the specified key and IV.
            aesAlg = new RijndaelManaged();
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            msEncrypt = new MemoryStream();
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {

                    //Write all data to the stream.
                    swEncrypt.Write(plainText);
                }
            }

        }
        finally
        {

            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        // Return the encrypted bytes from the memory stream.
        return msEncrypt.ToArray();

    }
도움이 되었습니까?

해결책

일반 텍스트의 크기는 중요하지 않습니다. Decryptstringfrombytes_aes (byte [] ciphertext, byte [] key, byte [] iv) 메소드의 암호화 바이트와 함께 정확히 동일한 IV와 키를 사용해야합니다. 그것은 당신에게 입력 한 일반 텍스트로 돌아갑니다.

예를 들어:


string plain_text = "Cool this works";
byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                                           0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
byte[] key = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
                                           0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
byte[] encrytped_text = encryptStringToBytes_AES(plain_text, key, iv);
string plain_text_again = decryptStringFromBytes_AES(encrypted_text, key, iv);

여기에서는 일반 텍스트와 일반 텍스트가 동일하다는 것을 알 수 있습니다. 이제 계속해서 Plain_Text를 원하는 모든 것으로 변경하고 이것이 제대로 작동하는지 확인하십시오.

Rijndaelmanaged의 기본값은 다음과 같습니다.
블록 크기 : 128
키 화 : 256
모드 : ciphermode.cbc
패딩 : PaddingMode.pkcs7

유효한 IV 크기는 다음과 같습니다.
128, 192, 256 비트 (이것은 블록 크기입니다. 사용중인 크기 IV로 설정하십시오)
유효한 키 크기는 다음과 같습니다.
128, 192, 256 비트 (키즈, 사용중인 크기 키로 설정하십시오)

이것은 바이트 [] IV가 16, 24 또는 32 바이트 (위의 예에서 16 바이트) 일 수 있고 바이트 [] 키는 16, 24 또는 32 바이트 (위의 예에서는 16 바이트) 일 수 있음을 의미합니다. ).

도움이되기를 바랍니다.

다른 팁

당신은 그것을 위해 패딩이 필요합니다. 실제로 링크 한 페이지에는 패딩에 대한 예제 (C ++)가 있습니다.

패딩을 사용하면 비 표준 블록 크기를 암호화 할 수 있습니다.

문자열을 유니 코드 바이트 표현으로 변환하지 마십시오. 올바른 길이를 확인하기가 너무 어렵고 충분한 무작위 배정을 제공하지 않습니다.

다음을 수행 할 수 있습니다. 사용하십시오 키 파생 함수. 함수 입력에 대한 고정 길이 바이트 배열을 원합니다. 이것이 무엇입니다 RFC2898 최고입니다.

따라서 새로운 RFC2898 객체를 만듭니다.

using PBKDF2 = System.Security.Cryptography.Rfc2898DeriveBytes;

class Example {
    byte[] mySalt = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

    void Initialize( string password ) {
        PBKDF2 kdf = new PBKDF2( password, mySalt );
        // Then you have your algorithm
        // When you need a key: use:
        byte[] key = kdf.GetBytes( 16 ); // for a 128-bit key (16*8=128)

        // You can specify how many bytes you need. Same for IV.
        byte[] iv = kdf.GetBytes( 16 ); // 128 bits again.

        // And then call your constructor, etc.
        // ...
    }
}

내가 이것을 어떻게 사용했는지에 대한 예를 들어, 확인하십시오 Rijndael을 사용한 나의 프로젝트. 문자열을 가져 와서 위의 방법을 사용하여 키 및 IV 바이트 배열을 가져 오는 비밀번호 단계가 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top