2012-11-20 2 views
1

구성 파일을 쓰고 읽는 프로그램이 있습니다. 필자는 vb.net에서 RijndaelManaged 개체를 사용하여 전체 파일을 암호화하고 키와 초기화 벡터에 동일한 값을 사용하여 암호를 해독 할 때 읽습니다.vb.net의 암호화/암호 해독이 항상 같은 값을 반환하지는 않습니다.

내 개발 컴퓨터와 다른 많은 컴퓨터에서 모두 잘 작동합니다. 그러나 일부 PC는 동일한 프로그램을 사용하여 파일을 암호화/해독 할 수 없습니다.

이 암호화 개체에는 차단을 방지하기 위해 무엇이 필요하며 대신 사용 하시겠습니까?

감사

편집 : 여기에 내가 암호화하고 해독하는 데 사용하는 코드입니다 : 내 메인 컴퓨터에서 바이트를 암호화하는 경우, 내가 볼 수에서 무슨 일이, 내가 어떤 PC에서 그것을 decypt 수 있습니다. 그러나 다른 PC에서 바이트를 암호화하면 모든 PC에서 해독 할 수 없습니다. 또한, 파일의 내용을 살펴보면 전혀 같지 않게 보입니다. 내가 돌아 다니는 일반적인 방법은 파일 (보통 XML)에서 memorystream을 생성하고 암호화/해독하는 것입니다.

Public Shared Function EncryptBytes(ByVal strContenu() As Byte, ByVal initVectorBytes() As Byte, ByVal saltValueBytes() As Byte) As Byte() 

    ' Convert our plaintext into a byte array. 
    ' Let us assume that plaintext contains UTF8-encoded characters. 
    Dim plainTextBytes As Byte() = strContenu 
    'plainTextBytes = System.Text.Encoding.Unicode.GetBytes(strMessage) 

    Dim strPassPhrase As String = "d%6&?76dhd8?532LDhds8!7?&?8&?dhcv77" 

    Dim strHashAlgorithm As String = "SHA1" 

    Dim intPswdIterations As Integer = 2 

    ' First, we must create a password, from which the key will be derived. 
    ' This password will be generated from the specified passphrase and 
    ' salt value. The password will be created using the specified hash 
    ' algorithm. Password creation can be done in several iterations. 
    Dim password As PasswordDeriveBytes 
    password = New PasswordDeriveBytes(strPassPhrase, _ 
             saltValueBytes, _ 
             strHashAlgorithm, _ 
             intPswdIterations) 

    ' Use the password to generate pseudo-random bytes for the encryption 
    ' key. Specify the size of the key in bytes (instead of bits). 
    Dim keyBytes As Byte() 
    keyBytes = password.GetBytes(32) 

    ' Create uninitialized Rijndael encryption object. 
    Dim symmetricKey As RijndaelManaged 
    symmetricKey = New RijndaelManaged() 

    ' It is reasonable to set encryption mode to Cipher Block Chaining 
    ' (CBC). Use default options for other symmetric key parameters. 
    symmetricKey.Mode = CipherMode.CBC 

    ' Generate encryptor from the existing key bytes and initialization 
    ' vector. Key size will be defined based on the number of the key 
    ' bytes. 
    Dim encryptor As ICryptoTransform 
    encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes) 

    ' Define memory stream which will be used to hold encrypted data. 
    Dim memoryStream As System.IO.MemoryStream 
    memoryStream = New System.IO.MemoryStream() 

    ' Define cryptographic stream (always use Write mode for encryption). 
    Dim cryptoStream As CryptoStream 
    cryptoStream = New CryptoStream(memoryStream, _ 
            encryptor, _ 
            CryptoStreamMode.Write) 
    ' Start encrypting. 
    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length) 

    ' Finish encrypting. 
    cryptoStream.FlushFinalBlock() 

    ' Convert our encrypted data from a memory stream into a byte array. 
    Dim cipherTextBytes As Byte() 
    cipherTextBytes = memoryStream.ToArray() 

    ' Close both streams. 
    memoryStream.Close() 
    cryptoStream.Close() 

    ' Convert encrypted data into a base64-encoded string. 
    'Dim cipherText As String 
    'cipherText = 
    Return cipherTextBytes 

    ' Return encrypted string. 
    'Return cipherText 

End Function 

Public Shared Function DecryptBytes(ByVal strContenuEncrypte() As Byte, ByVal initVectorBytes() As Byte, ByVal saltValueBytes() As Byte) As Byte() 

    ' Convert strings defining encryption key characteristics into byte 
    ' arrays. Let us assume that strings only contain ASCII codes. 
    ' If strings include Unicode characters, use Unicode, UTF7, or UTF8 
    ' encoding. 

    ' Convert our ciphertext into a byte array. 
    Dim cipherTextBytes As Byte() = strContenuEncrypte 

    Dim strPassPhrase As String = "d%6&?76dhd8DSDhds8!7?&?8&?dhcv77" 

    Dim strHashAlgorithm As String = "SHA1" 

    Dim intPswdIterations As Integer = 2 

    ' First, we must create a password, from which the key will be 
    ' derived. This password will be generated from the specified 
    ' passphrase and salt value. The password will be created using 
    ' the specified hash algorithm. Password creation can be done in 
    ' several iterations. 
    Dim password As PasswordDeriveBytes 
    password = New PasswordDeriveBytes(strPassPhrase, _ 
             saltValueBytes, _ 
             strHashAlgorithm, _ 
             intPswdIterations) 

    ' Use the password to generate pseudo-random bytes for the encryption 
    ' key. Specify the size of the key in bytes (instead of bits). 
    Dim keyBytes As Byte() 
    keyBytes = password.GetBytes(32) 

    ' Create uninitialized Rijndael encryption object. 
    Dim symmetricKey As RijndaelManaged 
    symmetricKey = New RijndaelManaged() 

    ' It is reasonable to set encryption mode to Cipher Block Chaining 
    ' (CBC). Use default options for other symmetric key parameters. 
    symmetricKey.Mode = CipherMode.CBC 

    ' Generate decryptor from the existing key bytes and initialization 
    ' vector. Key size will be defined based on the number of the key 
    ' bytes. 
    Dim decryptor As ICryptoTransform 
    decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes) 

    ' Define memory stream which will be used to hold encrypted data. 
    Dim memoryStream As System.IO.MemoryStream 
    memoryStream = New System.IO.MemoryStream(cipherTextBytes) 

    ' Define memory stream which will be used to hold encrypted data. 
    Dim cryptoStream As CryptoStream 
    cryptoStream = New CryptoStream(memoryStream, _ 
            decryptor, _ 
            CryptoStreamMode.Read) 

    ' Since at this point we don't know what the size of decrypted data 
    ' will be, allocate the buffer long enough to hold ciphertext; 
    ' plaintext is never longer than ciphertext. 
    Dim plainTextBytes As Byte() 
    ReDim plainTextBytes(cipherTextBytes.Length) 

    ' Start decrypting. 
    Dim decryptedByteCount As Integer 
    decryptedByteCount = cryptoStream.Read(plainTextBytes, _ 
              0, _ 
              plainTextBytes.Length) 

    ' Close both streams. 
    memoryStream.Close() 
    cryptoStream.Close() 

    ' Convert decrypted data into a string. 
    ' Let us assume that the original plaintext string was UTF8-encoded. 
    Dim plainText As String 
    plainText = System.Text.Encoding.Unicode.GetString(plainTextBytes, _ 
             0, _ 
             decryptedByteCount) 

    ' Return decrypted string. 
    Return plainTextBytes 


End Function 
+1

암호화 알고리즘 코드를 게시 할 수 있습니까? – nerdybeardo

답변

1

일반 .NET 대신 Mono를 런타임으로 사용하는 경우 PasswordDeriveBytes은 20보다 큰 출력에 실패합니다. PasswordDeriveBytes은 더 많은 출력이 요청 될 때 알려지지 않은 독점적 인 비 결정적이며 깨어진 암호 학적으로 안전하지 않은 방법을 사용합니다 해시 출력보다 PasswordDeriveBytes 내에서 제공 할 수 있습니다. This has been marked as no-fix by the Mono developers..

가장 좋은 방법은 PBKDF1 대신 PBKDF2를 구현하는 Rfc2898DeriveBytes으로 업그레이드하는 것입니다. PBKDF2는 모든 구현이 지정된대로 동작하도록 출력 양을 확장하는 방법을 정의합니다.

해시 함수가 제공하는 것보다 많은 출력이 필요한 경우 PBKDF2 출력에 대해 HKDF와 같은 KBKDF를 사용하는 것이 더 안전합니다. PKBDF2는 더 많은 데이터를 생성하기 위해 또 다른 전체 라운드 세트를 필요로하며 이는 일반 사용자 대신 공격자를 선호 할 수 있으며 요청 된 바이트 수에 따라 CPU로드를 두 배 또는 세 배로 늘릴 수 있습니다.

[편집] 당신에게 공급하기 전에 바이트로 변환 더 낫다 있도록

는 또한, 문자열가 문자 인코딩을 지정하지 않는 암호를 취 PasswordDeriveBytes의 생성자를 사용할 수 있습니다 생성자.

대부분의 관찰에 따르면 둘 다 UTF-8을 사용하는 것 같습니다. 자바와 같은 다른 런타임은이 점에서 다를 수 있습니다.

0

텍스트 모드로 파일을 쓰고 읽고 있습니까? 암호화 된 데이터에 0x1A (EOF, ctrl-z)가 포함될 경우 읽기가 너무 일찍 중단 될 수 있으며 몇 바이트로 해독 할 수 있습니다.

+0

파일 자체는 XML 파일이며 파일로 암호화하기 전에 메모리 스트림에 씁니다. 어떻게 이것이 한 PC에서 다른 PC로 다를 수 있습니까? –

+0

'파일로 암호화'란 무엇을 의미합니까? 데이터를 암호화하거나 데이터를 파일로 저장할 수 있습니다. 암호화 된 데이터가 모든 컴퓨터에서 동일하거나 다른 암호화 키를 사용합니까? 그리고 모에가 제안한대로 : 관련 코드를 게시하십시오. – Jeff

0

120Gb 파일을 바이트()로 업로드 할 수 없습니다. 또는 미친 기계가 있습니다. 바이트로 업로드하여 RAM에 업로드하십시오.

Dim fStream As FileStream = New FileStream("Encrypted.Encrypted", FileMode.Create) 
     Dim cryptoStream As New CryptoStream(fStream, Encryptor, CryptoStreamMode.Write) 
     Using UploadFile As FileStream = New FileStream(OpenfileDialog.FileName, FileMode.Open) 
      For i = 0 To UploadFile.Length - 1 
       Dim NewByte As New Byte 
       NewByte = UploadFile.ReadByte 
       cryptoStream.WriteByte(NewByte) 
      Next 
     End Using 

     cryptoStream.FlushFinalBlock() 
     cryptoStream.Close() 
     fStream.Close() 
관련 문제