C# 与RNGCryptoServiceProvider等效的Javascript
我正在使用C# 与RNGCryptoServiceProvider等效的Javascript,c#,javascript,C#,Javascript,我正在使用RNGCryptoServiceProvider为C#中的某些东西生成一些简单的键,但我有一种情况,需要在客户端使用Javascript生成这些键 我可以直接调用服务器并获取它,但我想避免在服务器负载已经很重的情况下再次请求服务器。我使用的代码如下;但是,我在Javascript中找不到与RNGCryptoServiceProvider等价的,或者类似的东西 我可以翻译这里几乎所有的东西,除了那一节课。。。这真的开始困扰我了 /// <summary> /// Genera
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();
}
}
//
///生成具有特定字符的给定长度的密钥。
///
///
///要生成的密钥的长度。
///
///
///密钥中允许的字符。
///
///
///生成的密钥。
///
公共静态字符串创建(int-length,string allowedChars=“abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvxyz”){
如果(长度<0)抛出新ArgumentOutOfRangeException(“长度”,“长度不能小于零”);
if(string.IsNullOrEmpty(allowedChars))抛出新的ArgumentException(“allowedChars不能为空”);
常量int字节大小=0x100;
var allowedCharSet=new HashSet(allowedChars.ToArray();
如果(byteSize 如果(outOfRangeStart我强烈建议您使用服务器端调用,因为JavaScript是客户端语言,对于安全密钥来说并不安全,因为它可以查看完整的算法,并且重新设计可能会暴露您的值
因此,一次对服务器端的调用并没有那么昂贵。这是一个公平的论点。我没有对这种优势进行太多评估,因为这些优势更多的是为了识别而不是实际的安全性。它只是生成一些“索引”这样可以更容易地引用集合中的不同项。我可能会以服务器端调用结束。您对该类有更具体的问题吗?