我正在使用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();
}
}
你對這個班有更具體的問題嗎? –