/// <summary> /// Generates a new transfer code. /// </summary> /// <param name="length">Length of the code.</param> /// <param name="randomSource">Cryptographically safe random generator.</param> /// <returns>New transfer code.</returns> public static string GenerateCode(int length, ICryptoRandomService randomSource) { StringBuilder sb = new StringBuilder(); int remainingLength = length; do { int binaryLength = (int)Math.Floor((remainingLength * 3.0 / 4.0) + 1.0); byte[] binaryString = randomSource.GetRandomBytes(binaryLength); // We take advantage of the fast base64 encoding string base64String = Convert.ToBase64String(binaryString); foreach (char letter in base64String) { if (UnmixableAlphabet.IsOfCorrectAlphabet(letter)) { sb.Append(letter); } } // If too many characters have been removed, we repeat the procedure remainingLength = length - sb.Length; }while (remainingLength > 0); if (sb.Length > length) { sb.Remove(length, sb.Length - length); } return(sb.ToString()); }
public void TransferCodeIsOfCorrectAlphabet() { for (int length = 0; length < 999; length++) { string code = TransferCode.GenerateCode(length, CommonMocksAndStubs.CryptoRandomService()); Assert.IsTrue(UnmixableAlphabet.IsOfCorrectAlphabet(code)); } }
public void IsOfCorrectAlphabetWorksCorrectly() { for (int i = 0; i < 512; i++) { bool evaluated = UnmixableAlphabet.IsOfCorrectAlphabet((char)i); bool expected = IsOfCorrectAlphabet((char)i); Assert.AreEqual(expected, evaluated); } }
/// <summary> /// Tries to read unser input and brings it into a wellformed format without whitespaces. /// </summary> /// <param name="code">User input to validate.</param> /// <param name="sanitizedCode">Wellformed code.</param> /// <returns>Returns true if the user input was a valid code, otherwise false.</returns> public static bool TrySanitizeUserInput(string code, out string sanitizedCode) { sanitizedCode = null; if (string.IsNullOrWhiteSpace(code)) { return(false); } // remove whitespaces sanitizedCode = code.Replace(" ", string.Empty).Replace("-", string.Empty); if (sanitizedCode.Length != CodeLength) { return(false); } if (!UnmixableAlphabet.IsOfCorrectAlphabet(sanitizedCode)) { return(false); } return(true); }