2011-04-13 4 views
4

인증 라이브러리에서 bcrypt 지원을 허용하려고합니다. 현재 문제 중 하나는 해머가 유형이 HashAlgorithm 인 것으로 가정한다는 것입니다. Bcrypt.net은이 클래스를 구현하지 않습니다. 또한, 그것은 봉쇄되어 있으므로 내 자신의 지점을 만들어서 수정해야 할 것입니다. 이미 HashAlgorithm을 구현 한 더 나은 대안이 있습니까?. HashAlgorithm을 구현하는 bcrypt의 .Net 구현?

답변

6

이 시도 :

public class BCryptHasher : HashAlgorithm 
{ 
    private MemoryStream passwordStream = null; 

    protected override void HashCore(byte[] array, int ibStart, int cbSize) 
    { 
     if (passwordStream == null || Salt == null) 
      Initialize(); 

     passwordStream.Write(array, ibStart, cbSize); 
    } 

    protected override byte[] HashFinal() 
    { 
     passwordStream.Flush(); 

     // Get the hash 
     return Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(Encoding.UTF8.GetString(passwordStream.ToArray()), Salt));    
    } 

    public override void Initialize() 
    { 
     passwordStream = new MemoryStream(); 

     // Set up salt 
     if (Salt == null) 
     { 
      if (WorkFactor == 0) 
       Salt = BCrypt.Net.BCrypt.GenerateSalt(); 
      else 
       Salt = BCrypt.Net.BCrypt.GenerateSalt(WorkFactor); 
     } 
    } 

    public int WorkFactor { get; set; } 

    public string Salt { get; set; } 

    public bool Verify(string plain, string hash) 
    { 
     return BCrypt.Net.BCrypt.Verify(plain, hash); 
    } 
} 

사용법 : 또한

BCryptHasher hasher = new BCryptHasher(); 
string pw = "abc"; 
string hash = Encoding.UTF8.GetString(hasher.ComputeHash(Encoding.UTF8.GetBytes(pw))); 

, 난 당신이 암호 해시와 일치하는지 확인할 수 있도록 도우미는 방법을 확인하지만, 그냥 경우이를 제거 할 수 있습니다 추가 기본 BCrypt.Verify를 호출하십시오.

string pw = "abc"; 
hasher.Salt = "$2a$06$If6bvum7DFjUnE9p2uDeDu"; 
string hash = Encoding.UTF8.GetString(hasher.ComputeHash(Encoding.UTF8.GetBytes(pw))); 

내가 BCrypt와 그것을 시도 : 당신이 해시를하기 전에 당신이 미리 계산 염 또는 새로운 염을 생성하는 작업 요소에 전달할 수 있도록

bool matches = hasher.Verify(pw, hash); 

나는 몇 가지 추가 속성을 추가 "$ 2a $ 06 $ If6bvum7DFjUnE9p2uDeDu"의 salt로 테스트 케이스 "abc"를 만들고 올바른 해쉬를 얻었습니다.

+0

완벽 해 보입니다. 나는 오늘 밤 그것을 시도 할 것이고, 모든 것이 잘된다면, 당신은 정말로 내게 큰 호의를 베풀 것이다. – Earlz

+2

미래의 시청자들에게 : 이것은 전통적으로 HashAlgorithm과 호환되지 않는다는 것에주의하라. BCrypt가 작동하는 방식 때문에, 내가 "추적 된 소금"이라고 부르는 것을 가지고 있습니다. 해시 된 암호 나 그와 같은 것에 소금을 추가 할 수는 없으며 암호에 대해 동일한 해시를 얻으려면 일반 텍스트 (또는 암호화 된) 어딘가에 명시 적으로 소금을 저장해야합니다. – Earlz