2014-01-18 1 views
1

RNGCryptoServiceProvider을 사용하여 C#에서 무언가를위한 간단한 키를 생성하지만 자바를 사용하여 클라이언트 측에서 생성해야하는 상황이 있습니다.RNGCryptoServiceProvider에 해당하는 자바 스크립트

그냥 서버를 호출하여 가져올 수는 있지만 이미 서버로드가 많은 서버에서는 다른 서버 요청을 피하기를 원했습니다. 내가 사용하고있는 코드는 다음과 같습니다. 그래도 RNGCryptoServiceProvider에 해당하는 자바 스크립트를 찾을 수 없습니다.

내가 그 하나 개의 클래스를 제외하고 여기에 거의 모든 것을 번역 할 수 있습니다 ... 정말

/// <summary> 
/// Generate a key of a given length with specific characters. 
/// </summary> 
/// <param name="length"> 
/// The length of the key to generate. 
/// </param> 
/// <param name="allowedChars"> 
/// The characters allowed in the key. 
/// </param> 
/// <returns> 
/// A generated key. 
/// </returns> 
public static string Create(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") { 
    if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be less than zero."); 
    if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty."); 

    const int byteSize = 0x100; 
    var allowedCharSet = new HashSet<char>(allowedChars).ToArray(); 
    if (byteSize < allowedCharSet.Length) throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize)); 

    // Guid.NewGuid and System.Random are not particularly random. By using a 
    // cryptographically-secure random number generator, the caller is always 
    // protected, regardless of use. 
    using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) { 
     var result = new StringBuilder(); 
     var buf = new byte[128]; 
     while (result.Length < length) { 
      rng.GetBytes(buf); 
      for (var i = 0; i < buf.Length && result.Length < length; ++i) { 
       // Divide the byte into allowedCharSet-sized groups. If the 
       // random value falls into the last group and the last group is 
       // too small to choose from the entire allowedCharSet, ignore 
       // the value in order to avoid biasing the result. 
       var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length); 
       if (outOfRangeStart <= buf[i]) continue; 
       result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]); 
      } 
     } 
     return result.ToString(); 
    } 
} 
+0

해당 클래스에 대해 더 구체적인 질문이 있으십니까? –

답변

0

난 강력하게 자바 스크립트로, 당신은 서버 양면 통화 이동하는 것이 좋습니다 ... 귀찮게하기 시작 클라이언트 측 언어이고 보안 키에 대해서는 안전하지 않습니다. 완전한 알고리즘을 볼 수 있고 다시 엔지니어링하면 가치가 노출 될 수 있습니다.

그래서 서버 쪽을 한 번 호출하면 비용이 많이 들지 않습니다.

+1

그것은 공정한 주장입니다. 나는 실제 보안보다 식별을 위해 더 많은 힘을 많이 쏟아 부었다. 모음의 여러 항목을보다 쉽게 ​​참조 할 수 있도록 "색인"을 생성하는 것입니다. 아마도 서버 측 호출로 끝날 것입니다. – Ciel

관련 문제