2016-11-10 8 views
-1

다음 코드를 가지고 있으며 거의 ​​2 년간 작동했습니다. 그러나 이제 우리는 Padding에 대한 임의의 문제를보기 시작했습니다. 내가 무작위로 말할 때, 나는 같은 일이 어느 날 일하지만 다른 날에는 일하지 않는다는 것을 의미합니다. 그리고 언젠가는 무작위로 일하기로 결정합니다.기존 암호화/암호 해독 코드에서 패딩 옵션을 변경하는 방법은 무엇입니까?

위의 답변에서 언급 한 것처럼 패딩을 추가하지 않으면 이전에 암호화 된 파일을 모두 망칠 수 있습니다. 나는 다른 방법을 GOTO 문을 사용하여 catch 블록에서이 방법으로 만들 때와 같은 방법으로 암호화 키를 변경했을 때 생각했다. 또는 은 패딩을 None으로 변경하는 더 좋은 방법이 있습니까?

/// <summary> 
/// 
/// </summary> 
[Serializable] 
public static class EncryptDecrypt 
{ 
    private static string EncryptionKey_old = "MAKV2SPBNI99212"; 
    private static string EncryptionKey = "Yi9BpGG1cXR01gBwGPZRTOznoJHpkGBOzisBg5jl3iRu48yhcFGdZu76fDpa5FUu"; 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="clearText"></param> 
    /// <returns></returns> 
    public static string Encrypt(string clearText) 
    { 
     byte[] whitebs = Encoding.Unicode.GetBytes(clearText); 

     using (Aes encryptor = Aes.Create()) 
     { 

      Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 

      encryptor.Key = pdb.GetBytes(32); 

      encryptor.IV = pdb.GetBytes(16); 
      encryptor.Mode = CipherMode.ECB; 
      encryptor.Padding = PaddingMode.PKCS7; 

      using (MemoryStream ms = new MemoryStream()) 
      { 

       using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) 
       { 

        cs.Write(whitebs, 0, whitebs.Length); 
        cs.FlushFinalBlock(); 
        cs.Close(); 
       } 
       clearText = Convert.ToBase64String(ms.ToArray()); 
      } 
     } 
     return clearText.EndsWith("==") ? clearText.Remove(clearText.Length - 2) : clearText; 
    } 
    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="cipherText"></param> 
    /// <returns></returns> 
    public static string Decrypt(string cipherText) 
    { 
     int attempts = 0; 
     string exception = string.Empty; 


     StartHere: 
     cipherText = cipherText.Replace(" ", "+"); 

     byte[] cipherBytes; 
     try { cipherBytes = Convert.FromBase64String(cipherText); } 
     catch { cipherBytes = Convert.FromBase64String(cipherText + "=="); } 

     using (Aes encryptor = Aes.Create()) 
     { 

      Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 

      encryptor.Key = pdb.GetBytes(32); 

      encryptor.IV = pdb.GetBytes(16); 
      encryptor.Mode = CipherMode.ECB; 
      encryptor.Padding = PaddingMode.PKCS7; 
      try 
      { 
       using (MemoryStream ms = new MemoryStream()) 
       { 

        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) 
        { 

         cs.Write(cipherBytes, 0, cipherBytes.Length); 
         cs.FlushFinalBlock(); 
         cs.Close(); 
        } 

        cipherText = Encoding.Unicode.GetString(ms.ToArray()); 

       } 
      } 
      catch 
      { 
       if (attempts == 2) throw; 
       EncryptionKey = EncryptionKey_old; 
       attempts++; 
       goto StartHere; 
      } 
     } 
     return cipherText; 
    } 
    ' 

또한 우리가이 코드를 사용하여 암호화 된 파일의 수천이 있기 때문에 내가 그 일에 대해 갈 것입니다 방법을 모르는 좋은 생각이 아니다 지금 변경.

+0

이인가요 올바른 패딩입니다 방금 공개 인터넷에 올린 하드 코드 된 암호화 키가 있습니까? – Blorgbeard

+0

아니, 이전 하나는 진짜지만 더 이상 사용되지 않았습니다. –

+0

대신 왜 이러한 패딩 문제가 발생하는지 파악하려고합니다. 그 사실을 알면 다른 것을 바꾸는 것에 대해 걱정할 필요가 없습니다. 당신은 잘못된 방식으로 문제에 접근하고 있습니다. –

답변

2

해독이 성공했는지 확인하는 데 패딩 오류가 사용 된 것 같습니다. 잘못되어 작동하지 않습니다. 성공적인 암호 해독을 결정하는 다른 방법이 필요합니다.이 경우 정확한 키가 사용됩니다.

PKCS#7 padding을 참조하십시오.

잘못된 키로 암호 해독하면 결과는 본질적으로 임의의 데이터가되고 마지막 바이트는 올바른 패딩 0x01이 될 확률이 1/256이며 패딩 오류가보고되지 않습니다. 더 적은 범위에서 다른 유효한 패딩이 임의로 발생합니다.

올바른 해독을 얻었는지 확인하기 위해 다른 방법이 필요합니다. 일반적으로 MAC을 사용하여 암호화를 인증합니다. 그러나 알려진 데이터의 일부일 수 있습니다. 일반적으로 crib이라고하며 성공률은 고유성으로 결정됩니다.

재 : 패딩 : 암호화 할 데이터의 길이가 블록 크기의 정확한 배수가 항상 (AES를위한 16 바이트)하지 않는 한 패딩이 필요하고 PKCS # 7 패딩