Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to implement your own RNG provider

Rob Janssen edited this pageNov 25, 2015 ·3 revisions

This library also comes with three 'built-in' RNG providers (Random Number Generator). The RNG provider generates a number of random bytes and returns these bytes as a string. These values are then used to create the secret. By default (no RNG provider specified) TwoFactorAuth.Net will use theDefaultRngProvider. Each of the providers use their own method of generating a random sequence of bytes. TheDefaultRngProvider returns a cryptographically secure sequence of random bytes whereas theHashRngProvider andPrngProvider return non-cryptographically secure sequences.

You can easily implement your own RNGProvider by simply implementing theIRngProvider interface. Some of the 'built-in' RNG providers have some constructor arguments that allow you to 'tweak' some of the settings to use when creating the random bytes such as which hashing algorithm to use. I encourage you to have a look at some of the 'built-in' RNG providers for details and theIRngProvider interface.

Demonstration

Let's try implementing our own!

  1. Create a classMyLCGProvider.cs
usingSystem;namespaceMyNameSpace{publicclassMyLCGProvider{}}
  1. Implement theIRngProvider interface:
usingSystem;usingTwoFactorAuthNet.Providers.Rng;namespaceMyNameSpace{publicclassMyLCGProvider:IRngProvider{}}
  1. Implement theIRngProvider interface members:
usingSystem;usingTwoFactorAuthNet.Providers.Rng;namespaceMyNameSpace{publicclassMyLCGProvider:IRngProvider{publicboolIsCryptographicallySecure{get{returnfalse;}}publicbyte[]GetRandomBytes(intbytes){// https://en.wikipedia.org/wiki/Linear_congruential_generatorvarresult=newbyte[bytes];intm=int.MaxValue,a=2147483629,c=2147483587;unchecked{intseed=(int)(DateTime.Now.Ticks&0xFFFFFFFF);for(inti=0;i<bytes;i++){seed=(a*seed+c)%m;result[i]=(byte)(seed&0xFF);}}}}}

NOTE: Please note that this RNG is intended as an example. It isnot cryptographically secure (altough this implementation has a fairly uniform distribution).

  1. Pass your newly created RNG provider to a TwoFactorAuth constructor overload that accepts anIRngProvider argument.

From here on thetfa instance will use your RNG provider.

See also:

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp