2014-01-18 55 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