summaryrefslogtreecommitdiffstats
path: root/src/Otp.NET/KeyGeneration.cs
diff options
context:
space:
mode:
Diffstat (limited to 'src/Otp.NET/KeyGeneration.cs')
-rw-r--r--src/Otp.NET/KeyGeneration.cs71
1 files changed, 71 insertions, 0 deletions
diff --git a/src/Otp.NET/KeyGeneration.cs b/src/Otp.NET/KeyGeneration.cs
new file mode 100644
index 0000000..7e5b613
--- /dev/null
+++ b/src/Otp.NET/KeyGeneration.cs
@@ -0,0 +1,71 @@
+/*
+Credits to Devin Martin and the original OtpSharp library:
+https://bitbucket.org/devinmartin/otp-sharp/overview
+
+Copyright (C) 2012 Devin Martin
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+*/
+
+namespace OtpNet
+{
+ /// <summary>
+ /// Helpers to work with keys
+ /// </summary>
+ public static class KeyGeneration
+ {
+ /// <summary>
+ /// Generates a random key in accordance with the RFC recommened length for each algorithm
+ /// </summary>
+ /// <param name="length">Key length</param>
+ /// <returns>The generated key</returns>
+ public static byte[] GenerateRandomKey(int length)
+ {
+ byte[] key = new byte[length];
+ using(var rnd = System.Security.Cryptography.RandomNumberGenerator.Create())
+ {
+ rnd.GetBytes(key);
+ return key;
+ }
+ }
+
+ /// <summary>
+ /// Generates a random key in accordance with the RFC recommened length for each algorithm
+ /// </summary>
+ /// <param name="mode">HashMode</param>
+ /// <returns>Key</returns>
+ public static byte[] GenerateRandomKey(OtpHashMode mode = OtpHashMode.Sha1)
+ {
+ return GenerateRandomKey(LengthForMode(mode));
+ }
+
+ private static int LengthForMode(OtpHashMode mode)
+ {
+ switch(mode)
+ {
+ case OtpHashMode.Sha256:
+ return 32;
+ case OtpHashMode.Sha512:
+ return 64;
+ default: //case OtpHashMode.Sha1:
+ return 20;
+ }
+ }
+ }
+} \ No newline at end of file