2014-01-18 90 views
1

我正在使用RNGCryptoServiceProvider爲C#中的某些東西生成一些簡單的鍵,但是我有一種情況需要使用Javascript在客戶端生成這些鍵。Javascript等價於RNGCryptoServiceProvider

我可以直接調用服務器並獲取它,但我想避免在已經服務器的重負載上發出另一個服務器請求。我使用的代碼如下:儘管如此,我無法在Javascript中找到相當於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

我強烈建議你去服務器調用片面,如JavaScript是客戶端語言,對安全密鑰不安全,因爲它可以查看完整的算法,重新設計可能會暴露您的價值。

所以一次調用服務器端並不昂貴。

+1

這是一個公平的論點。我並沒有在實力上投入很多股票,因爲這些更多的是用於識別而非實際的安全。這只是生成一些「索引」,以便可以更容易地引用集合中的不同項目。我可能會結束服務器端調用。 – Ciel