2016-10-21 19 views
-2

メッセージのAES CBC暗号化のためのC#実装を作成しようとしています。目標は、C実装が適切に暗号化を解除できるように、C#でメッセージを「適切に」暗号化することです。CとC#の実装のAES/CBC暗号化の違い

Cの復号化の実装は(OpenSSLを使用して)次のようになります。

/* Create and initialise the context */ 
    if(!(ctx = EVP_CIPHER_CTX_new())) { 
     handleErrors(); 
    } 

    if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (unsigned char*)key, (unsigned char*)iv)) { 
       handleErrors(); 
    } 

    if(1 != EVP_DecryptUpdate(ctx, (unsigned char*)plaintext, &len, (unsigned char*)encrypted_text, encrypted_text_len)) { 
     handleErrors(); 
    } 
    plaintext_len = len; 

    if(1 != EVP_DecryptFinal_ex(ctx, (unsigned char*)plaintext + len, &len)) { 
     //Error happens here... 
    } 

私は次のエラーを取得:私が試してみました

static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV) 
     { 
      byte[] encrypted; 
      // Create an Aes object 
      // with the specified key and IV. 
      using (Aes aesAlg = Aes.Create()) 
      { 
       aesAlg.Key = Key; 
       aesAlg.IV = IV; 
       aesAlg.Mode = CipherMode.CBC; 
       // Create a decrytor to perform the stream transform. 
       ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); 

       // Create the streams used for encryption. 
       using (MemoryStream 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); 
         } 
         encrypted = msEncrypt.ToArray(); 
        } 
       } 
      }  
      // Return the encrypted bytes from the memory stream. 
      return encrypted; 
     } 

error: digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:evp_enc.c:518: 

C#のコードをすべてのパディングモード、運がない。どのような問題が起こる可能性がありますか?

+0

あなたは 'char []'と 'byte []'でここで働いています。あなたは暗号文をどれくらい正確に移していますか?バイナリデータをコピーして貼り付けることはできません。 –

+0

swEncrypt.Write(plainText)の直後にも試してみてください。 追加swEncrypt.FlushFinalBlock(); – Kevin

+0

テスト目的のために、単にC#のファイルにバイトをダンプし、Cでそれらを読み取るだけです。 – user2296277

答えて

0

エラーは、encrypted_text_len % 16 != 0を示します。

ファイルから読み込んだ場合、あなたのバッファに偶発的な改行がないことを再確認してください。

関連する問題