2014-12-06 3 views
0

이 AES 샘플 코드가 작동하려고합니다. 그러나 나는 아무것도 내 cipherText 변수를 반환하지 않습니다. 나는 오류를 얻지 않고 아무것도 반환하지 않습니다. 여기서 내가 뭘 잘못하고 있니? 같은 일을 모두AES 암호 화기가 작동하지 않습니다.

public byte[] key { get; set; } 
public byte[] IV { get; set; } 
public byte[] ciphertext { get; set; } 
public string plainText { get; set; } 


public byte[] Encrypt(string InputPlaintext) 
{ 
    InputPlaintext = "attack at dawn"; 
    using (AesCryptoServiceProvider AESEncryptor = new AesCryptoServiceProvider()) 
    { 

     ////using the AesCryptoServiceProvider to generate the IV and Key 

     key = AESEncryptor.Key; 

     IV = AESEncryptor.IV; 

     ICryptoTransform encryptor = AESEncryptor.CreateEncryptor(key, IV); 

     using (MemoryStream msEncrypt = new MemoryStream()) 
     { 
      using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) 
      { 

       using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) 
       { 
        swEncrypt.Write(InputPlaintext); 
        ciphertext = msEncrypt.ToArray(); 
        return ciphertext; 
       } 
      } 
     } 
    }; 


} 

답변

3

세 가지 옵션,

중 하나가 csEncrypt.Close() 전화를 걸거나 메모리 스트림에 암호화 된 데이터를 플러시 csEncrypt.FlushFinalBlock()를 사용 - cipertext = msEncrypt.ToArray() 전에 호출합니다.

또는 cipher = msEncrypt.ToArray(); return cipertext;을 암호화 스트림에 쓰는 사용 블록 밖으로 이동하십시오. 첫 번째 추측 수 있습니다

csEncrypt.Flush() 아무것도 ...하지

http://reflector.webtropy.com/default.aspx/DotNET/DotNET/[email protected]/untmp/whidbey/REDBITS/ndp/clr/src/BCL/System/Security/Cryptography/[email protected]/1/[email protected]

public override void Flush() 
{ 
    return; 
}