문제

나는 실제로 구현하려고 매우 간단한 로그인 mecanism 앱 개발 수 있습니다.NET2.0 에 포함된 장치입니다.후에는 일부를 연구,발견했용하는 코드 샘플 수행하는 암호 해시:

암호를 저장하는 방법

불행하게도,하려고 할 때 그것을 사용하는 코드 샘플을 제기 코드에서 호출 byte.Parse 에 하위 문자열의 진수 문자열 SaltValue.정말을 이해하는 데 문제가 있 이유 때문에,나는 수행하지 않은 모든 변경 사항 코드입니다.

는 코드는 다음과 같습니다:

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;

private const int SaltValueSize = 4;

private static string GenerateSaltValue()
{
UnicodeEncoding utf16 = new UnicodeEncoding();

if (utf16 != null)
{
    // Create a random number object seeded from the value
    // of the last random seed value. This is done
    // interlocked because it is a static value and we want
    // it to roll forward safely.

    Random random = new Random(unchecked((int)DateTime.Now.Ticks));

    if (random != null)
    {
        // Create an array of random values.

        byte[] saltValue = new byte[SaltValueSize];

        random.NextBytes(saltValue);

        // Convert the salt value to a string. Note that the resulting string
        // will still be an array of binary values and not a printable string. 
        // Also it does not convert each byte to a double byte.


        //Original line :
        //string saltValueString = utf16.GetString(saltValue);
        //Replaced by :
        string saltValueString = utf16.GetString(saltValue, 0, SaltValueSize);

        // Return the salt value as a string.

        return saltValueString;
    }
}

return null;
}

private static string HashPassword(string clearData, string saltValue, HashAlgorithm hash)
{
UnicodeEncoding encoding = new UnicodeEncoding();

if (clearData != null && hash != null && encoding != null)
{
    // If the salt string is null or the length is invalid then
    // create a new valid salt value.

    if (saltValue == null)
    {
        // Generate a salt string.
        saltValue = GenerateSaltValue();
    }

    // Convert the salt string and the password string to a single
    // array of bytes. Note that the password string is Unicode and
    // therefore may or may not have a zero in every other byte.

    byte[] binarySaltValue = new byte[SaltValueSize];

    //FormatException raised here
    binarySaltValue[0] = byte.Parse(saltValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);
    binarySaltValue[1] = byte.Parse(saltValue.Substring(2, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);
    binarySaltValue[2] = byte.Parse(saltValue.Substring(4, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);
    binarySaltValue[3] = byte.Parse(saltValue.Substring(6, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture.NumberFormat);

//...
//Some more code
//...
}
}

나만을 변경 한 줄:

string saltValueString = utf16.GetString(saltValue);

하기

string saltValueString = utf16.GetString(saltValue, 0, SaltValueSize);

기 때문에 첫 번째 버전의 방법이 보이지 않는 것을 사용할 수 있는 임베디드 C#.하지만 어쨌든 난 테스트를 변경하지 않고 이 선(에 포함되지 않은 환경),그리고 그것은 여전히 상승 코드.

나는 복사 SaltValueSize 값을 다른 msdn 샘플 코드(는 관련):는 방법을 확인하는 암호

테스트는 제외:

HashPassword("youpi", null, new SHA1CryptoServiceProvider());

도움이 되었습니까?

해결책

문제는 사실에있는 당신의 GenerateSaltValue 메서드를 반환하지 않는 문자열의 hexademical 숫자입니다.

그것은 반환한 문자열의 일부를 임의의 문자,또는 일반적으로 유효하지 않을 수도 있습 hexademical 상징이 나를 위해 만들어진 문자열의 대부분이 중국 상형문자가 확인되지 않 parseable 여 바이트입니다.구문 분석 방법입니다.

또한,당신의 예에 관한 Microsoft Commerce Server -나는 아무 생각이 무엇이든지 그것입니다.

"솔루션:"

저는 이 모든 예고 싶으로 달성하기 위해 이 문자열 tohex-tobinary 전환수지만,그것을 성공적으로 실행하려면 GenerateSaltValue 의는 다음과 같습니다:

public static string ByteArrayToString(byte[] byteArray)
{
    StringBuilder hex = new StringBuilder(byteArray.Length * 2);

    foreach (byte b in byteArray)
        hex.AppendFormat("{0:x2}", b);

    return hex.ToString();
}

// Renamed GenerateSaltValue method
private static string GenerateHexSaltString()
{
    Random random = new Random();

    // Create an array of random values.
    byte[] saltValue = new byte[SaltValueSize];

    random.NextBytes(saltValue);

    string saltValueString = ByteArrayToString(saltValue);

    // Return the salt value as a string.
    return saltValueString;
}

과 당신의 프로그램이"일",감사 당신은 어떻게 변환하는 바이트 배열을 진수 문자열이며,그 반대가?

그러나:

  • 를 사용하여 임의의 소금 창조은 나쁜 생각이 아니다.
  • 문자열 tohex-tobinary 변환 외에도 빠른&가벼운 pc 클리너.
  • 와 다른 문제는...

그래서:

기사를 읽는 정말과 관련하여 C#암호 해싱과 암호화,다음과 같:

해쉬와 소금을 암호에의 C#

매우 세심한 위해 찾고 있는 동안 코드 예제다-그들은 사용할 수 있는 또 다른 버전이,플랫폼 또는 언어입니다.행운을 빕니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top