2017-12-03 3 views
1

SHA256을 사용하여 해시 코드를 생성하는 간단한 코드가 있지만 동일한 입력에 대해 다른 결과를 제공합니다. 그러나 예를 들어 _input= "test" 같은 따옴표로 동일한 문자열 값을 선언하면 동일한 결과가 반환됩니다.동일한 문자열 입력에 대해 다른 결과를주는 SHA256

public static System.String generateKey(System.String _input) 
{ 
    System.Byte[] convertedArr; 
    SHA256Managed sh = new System.Security.Cryptography.SHA256Managed(); 
     convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input)); 
     hashCode = System.Convert::ToBase64String(convertedArr); 
    return hashCode; 
    } 
+0

'_input'의 값은 무엇입니까? – aaron

+1

코드를 더 표시하십시오 - 입력 내용, FNSGenerateHashDetails 등 – DAXaholic

+1

[tag : C#]을 사용하지 않는 경우 태그를 지정하지 마십시오. –

답변

1

참고

convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));

해시에 입력 _inputString이지만 길이 _input에서 촬영되고, 그들이 동일하지 않다. _inputString! = _input.

는 함수 (고화질) :

public static System.String generateKey(System.String _input) 

현재 코드 :

convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input)); 

디버깅 (semio - 유사) 코드 : 입력 길이 이에

inputBytes = System.Text.Encoding::UTF8.GetBytes(_input) 
inputLength = System.Text.Encoding::UTF8.GetByteCount(_input) 
hashBytes = convertedArr = sh.ComputeHash(inputBytes, 0, inputLength); 

용이하게 확인할 수있다 . _input은 한 번만 사용되기 때문에 오류가 발생할 가능성이 적습니다.

참고 : 실제로 길이는 inputBytes에서 얻을 수 있지만 X ++에는 유창하지 않으므로 변경하지 않았습니다.

+0

감사합니다. zaph 아래에서 귀하의 것과 동일한 것을 사용하고 있습니다. _input 및 _inputString은 실수입니다. 그것은 동일합니다. inputBytes = System.Text.Encoding :: UTF8.GetBytes (_input) inputLength = System.Text.Encoding :: UTF8.GetByteCount (_input) hashBytes = convertedArr = sh.ComputeHash (inputBytes, 0, inputLength); inputLength와 inputBytes 모두에서 길이를 시도했지만 sh.ComputeHash가 매번 다른 이유는 확실하지 않습니다. inputBytes 및 inputLength는 항상 괜찮은 것 같습니다. 만약 내가 하드 코드와 프로그램에서 동일한 문자열을 선언하지만, 지금 매개 변수로 받아 들일 때가 없다. 지금은 단서가 없다. – Sweety

+0

입력이 다르기 때문에 출력이 다르다. 이것이 일어날 수있는 한 가지 방법은 length 매개 변수가 입력 데이터보다 크고 지정된 바이트 수를 얻기 위해 실제 입력 뒤에 오는 가비지 바이트를 사용하는 것입니다. 분명히'System.Security.Cryptography.SHA256Managed'가 작동합니다. 아직 읽지 않은 문서를 읽지 않았 으면 좋겠어요. – zaph

+0

당신은'ComputeHash (Byte [], Int32, Int32)'대신에'ComputeHash (Byte [])'를 시도 할 수 있습니다. 그러면 크기 변수가 제거됩니다. 또한'.Text.Encoding :: UTF8.GetBytes'는'Byte []'형을 반환합니까? 마지막으로 짧은 문자열 (예 : "TestMe")로 시도하고 [해시 계산기] (http://extranet.cryptomathic.com/hashcalc/index)와 같은 SHA-256 온라인 구현과 비교하여 작업 할 간단한 사례를 얻으십시오. . – zaph

관련 문제