我正在使用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();
}
}
你对这个班有更具体的问题吗? –