Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork56
How to implement your own RNG provider
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.
Let's try implementing our own!
- Create a class
MyLCGProvider.cs
usingSystem;namespaceMyNameSpace{publicclassMyLCGProvider{}}
- Implement the
IRngProviderinterface:
usingSystem;usingTwoFactorAuthNet.Providers.Rng;namespaceMyNameSpace{publicclassMyLCGProvider:IRngProvider{}}
- Implement the
IRngProviderinterface 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).
- Pass your newly created RNG provider to a TwoFactorAuth constructor overload that accepts an
IRngProviderargument.
From here on thetfa instance will use your RNG provider.