Javascript相当于RNGCryptoServiceProvider

时间:2014-01-18 18:47:09

标签: c# javascript

我正在使用RNGCryptoServiceProvider为C#中的某些内容生成一些简单的键,但我有一种情况需要在客户端使用Javascript生成这些键。

我可以调用服务器并获取它,但我想避免在已经服务器重负载上的另一个服务器请求。我使用的代码如下;我在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();
    }
}

1 个答案:

答案 0 :(得分:0)

我强烈建议您进行服务器端呼叫,因为JavaScript是客户端语言,对安全密钥不安全,因为它可以查看完整的算法,重新设计可能会暴露您的价值。

因此,对服务器端的一次调用并不昂贵。