diff --git a/KeeTrayTOTP.Tests/ExpiryTests.cs b/KeeTrayTOTP.Tests/ExpiryTests.cs index 8592348..2280203 100644 --- a/KeeTrayTOTP.Tests/ExpiryTests.cs +++ b/KeeTrayTOTP.Tests/ExpiryTests.cs @@ -5,7 +5,7 @@ namespace KeeTrayTOTP.Tests { [TestClass] - public class ExpiryTests + public class ExpiryTests { [TestMethod] public void IsExpired_ShouldReturnTrue_WhenExpiresIsTrueAndExpiryTimeInThePast() diff --git a/KeeTrayTOTP/FormHelp.cs b/KeeTrayTOTP/FormHelp.cs index a3f6ccd..6363b7e 100644 --- a/KeeTrayTOTP/FormHelp.cs +++ b/KeeTrayTOTP/FormHelp.cs @@ -41,7 +41,7 @@ private void FormHelp_Load(object sender, EventArgs e) Text = Localization.Strings.Help + @" - " + Localization.Strings.TrayTOTPPlugin; foreach (Control ctl in SplitContainerHelp.Panel2.Controls) { - ctl.Location = new Point(3,3); + ctl.Location = new Point(3, 3); ctl.Size = new Size(SplitContainerHelp.Panel2.Width - 3, SplitContainerHelp.Panel2.Height - 3); } TreeViewHelp.ExpandAll(); diff --git a/KeeTrayTOTP/FormSettings.cs b/KeeTrayTOTP/FormSettings.cs index c8d15b8..76d9682 100644 --- a/KeeTrayTOTP/FormSettings.cs +++ b/KeeTrayTOTP/FormSettings.cs @@ -16,7 +16,7 @@ internal partial class FormSettings : Form /// /// private delegate void SafeCallDelegate(object sender, DoWorkEventArgs e); - + /// /// Plugin Host. /// diff --git a/KeeTrayTOTP/Libraries/QRCoder/QRCode.cs b/KeeTrayTOTP/Libraries/QRCoder/QRCode.cs index 385834f..41f342b 100644 --- a/KeeTrayTOTP/Libraries/QRCoder/QRCode.cs +++ b/KeeTrayTOTP/Libraries/QRCoder/QRCode.cs @@ -26,14 +26,13 @@ using System.Drawing; using System.Drawing.Drawing2D; - namespace QRCoder { using System; - public class QRCode : IDisposable + public sealed class QRCode : IDisposable { - protected QRCodeData QrCodeData { get; set; } + public QRCodeData QrCodeData { get; private set; } public void Dispose() { @@ -112,12 +111,10 @@ public Bitmap GetGraphic(int pixelsPerModule, Color darkColor, Color lightColor, var lightBrush = new SolidBrush(lightColor); var darkBrush = new SolidBrush(darkColor); - for (var x = 0; x < size + offset; x = x + pixelsPerModule) { for (var y = 0; y < size + offset; y = y + pixelsPerModule) { - var module = this.QrCodeData.ModuleMatrix[(y + pixelsPerModule) / pixelsPerModule - 1][(x + pixelsPerModule) / pixelsPerModule - 1]; if (module) { diff --git a/KeeTrayTOTP/Libraries/QRCoder/QRCodeData.cs b/KeeTrayTOTP/Libraries/QRCoder/QRCodeData.cs index 5f56089..70b02ce 100644 --- a/KeeTrayTOTP/Libraries/QRCoder/QRCodeData.cs +++ b/KeeTrayTOTP/Libraries/QRCoder/QRCodeData.cs @@ -36,7 +36,7 @@ namespace QRCoder public class QRCodeData : IDisposable { public List ModuleMatrix { get; set; } - + public QRCodeData(int version) { this.Version = version; @@ -63,8 +63,8 @@ public QRCodeData(byte[] rawData, Compression compressMode) Stream4Methods.CopyTo(dstream, output); } bytes = new List(output.ToArray()); - } - } + } + } } else if (compressMode.Equals(Compression.GZip)) { @@ -99,9 +99,9 @@ public QRCodeData(byte[] rawData, Compression compressMode) for (int i = 7; i >= 0; i--) { modules.Enqueue((b & (1 << i)) != 0); - } + } } - + //Build module matrix this.ModuleMatrix = new List(); for (int y = 0; y < sideLen; y++) @@ -112,7 +112,6 @@ public QRCodeData(byte[] rawData, Compression compressMode) this.ModuleMatrix[y][x] = modules.Dequeue(); } } - } public byte[] GetRawData(Compression compressMode) @@ -120,8 +119,8 @@ public byte[] GetRawData(Compression compressMode) var bytes = new List(); //Add header - signature ("QRR") - bytes.AddRange(new byte[]{ 0x51, 0x52, 0x52, 0x00 }); - + bytes.AddRange(new byte[] { 0x51, 0x52, 0x52, 0x00 }); + //Add header - rowsize bytes.Add((byte)ModuleMatrix.Count); @@ -173,12 +172,12 @@ public byte[] GetRawData(Compression compressMode) } rawData = output.ToArray(); } - } + } return rawData; } public int Version { get; private set; } - + private static int ModulesPerSideFromVersion(int version) { return 21 + (version - 1) * 4; @@ -188,7 +187,6 @@ public void Dispose() { this.ModuleMatrix = null; this.Version = 0; - } public enum Compression diff --git a/KeeTrayTOTP/Libraries/QRCoder/QRCodeGenerator.cs b/KeeTrayTOTP/Libraries/QRCoder/QRCodeGenerator.cs index c671065..f2b2929 100644 --- a/KeeTrayTOTP/Libraries/QRCoder/QRCodeGenerator.cs +++ b/KeeTrayTOTP/Libraries/QRCoder/QRCodeGenerator.cs @@ -147,7 +147,6 @@ public QRCodeData CreateQrCode(string plainText, ECCLevel eccLevel, bool forceUt ); } - //Interleave code words var interleavedWordsSb = new StringBuilder(); for (var i = 0; i < Math.Max(eccInfo.CodewordsInGroup1, eccInfo.CodewordsInGroup2); i++) @@ -161,7 +160,6 @@ public QRCodeData CreateQrCode(string plainText, ECCLevel eccLevel, bool forceUt } } - for (var i = 0; i < eccInfo.ECCPerBlock; i++) { foreach (var codeBlock in codeWordWithECC) @@ -175,7 +173,6 @@ public QRCodeData CreateQrCode(string plainText, ECCLevel eccLevel, bool forceUt interleavedWordsSb.Append(new string('0', this.remainderBits[version - 1])); var interleavedData = interleavedWordsSb.ToString(); - //Place interleaved data on module matrix var qr = new QRCodeData(version); var blockedModules = new List(); @@ -196,7 +193,6 @@ public QRCodeData CreateQrCode(string plainText, ECCLevel eccLevel, bool forceUt ModulePlacer.PlaceVersion(ref qr, versionString); } - ModulePlacer.AddQuietZone(ref qr); return qr; } @@ -328,7 +324,6 @@ public static void PlaceFormat(ref QRCodeData qrCode, string formatStr) } } - public static int MaskCode(ref QRCodeData qrCode, int version, ref List blockedModules, ECCLevel eccLevel) { var patternName = string.Empty; @@ -336,9 +331,7 @@ public static int MaskCode(ref QRCodeData qrCode, int version, ref List blockedModules) { var size = qrCode.ModuleMatrix.Count; @@ -654,7 +645,6 @@ public static int Score(ref QRCodeData qrCode) lastValRow = qrCode.ModuleMatrix[y][x]; - if (qrCode.ModuleMatrix[x][y] == lastValColumn) { modInColumn++; @@ -677,7 +667,6 @@ public static int Score(ref QRCodeData qrCode) } } - //Penalty 2 for (var y = 0; y < size - 1; y++) { @@ -772,7 +761,6 @@ public static int Score(ref QRCodeData qrCode) return score1 + score2 + score3 + score4; } } - } private List CalculateECCWords(string bitString, ECCInfo eccInfo) @@ -840,7 +828,7 @@ private Polynom ConvertToDecNotation(Polynom poly) private int GetVersion(int length, EncodingMode encMode, ECCLevel eccLevel) { - var version = this.capacityTable.Where( + return this.capacityTable.Where( x => x.Details.Count( y => (y.ErrorCorrectionLevel == eccLevel && y.CapacityDict[encMode] >= Convert.ToInt32(length) @@ -852,7 +840,6 @@ private int GetVersion(int length, EncodingMode encMode, ECCLevel eccLevel) capacity = x.Details.Single(y => y.ErrorCorrectionLevel == eccLevel) .CapacityDict[encMode] }).Min(x => x.version); - return version; } private EncodingMode GetEncodingFromPlaintext(string plainText, bool forceUtf8) @@ -893,7 +880,6 @@ private Polynom CalculateMessagePolynom(string bitString) return messagePol; } - private Polynom CalculateGeneratorPolynom(int numEccWords) { var generatorPolynom = new Polynom(); @@ -1045,7 +1031,6 @@ private string PlainTextToBinaryNumeric(string plainText) var dec = Convert.ToInt32(plainText.Substring(0, 3)); codeText += DecToBin(dec, 10); plainText = plainText.Substring(3); - } if (plainText.Length == 2) { @@ -1069,7 +1054,6 @@ private string PlainTextToBinaryAlphanumeric(string plainText) var dec = this.alphanumEncDict[token[0]] * 45 + this.alphanumEncDict[token[1]]; codeText += DecToBin(dec, 11); plainText = plainText.Substring(2); - } if (plainText.Length > 0) { @@ -1081,8 +1065,7 @@ private string PlainTextToBinaryAlphanumeric(string plainText) private string PlainTextToBinaryECI(string plainText) { var codeText = string.Empty; - byte[] _bytes = Encoding.GetEncoding("ascii").GetBytes(plainText); - foreach (byte _byte in _bytes) + foreach (byte _byte in Encoding.GetEncoding("ascii").GetBytes(plainText)) { codeText += DecToBin(_byte, 8); } @@ -1137,7 +1120,6 @@ private string PlainTextToBinaryByte(string plainText, EciMode eciMode, bool utf return codeText; } - private Polynom XORPolynoms(Polynom messagePolynom, Polynom resPolynom) { var resultPolynom = new Polynom(); @@ -1168,7 +1150,6 @@ private Polynom XORPolynoms(Polynom messagePolynom, Polynom resPolynom) return resultPolynom; } - private Polynom MultiplyGeneratorPolynomByLeadterm(Polynom genPolynom, PolynomItem leadTerm, int lowerExponentBy) { var resultPolynom = new Polynom(); @@ -1184,7 +1165,6 @@ private Polynom MultiplyGeneratorPolynomByLeadterm(Polynom genPolynom, PolynomIt return resultPolynom; } - private Polynom MultiplyAlphaPolynoms(Polynom polynomBase, Polynom polynomMultiplier) { var resultPolynom = new Polynom(); @@ -1236,8 +1216,7 @@ private void CreateAlphanumEncDict() { this.alphanumEncDict = new Dictionary(); //alphanumEncTable.ToList().Select((x, i) => new { Chr = x, Index = i }).ToList().ForEach(x => this.alphanumEncDict.Add(x.Chr, x.Index)); - var resList = alphanumEncTable.ToList().Select((x, i) => new { Chr = x, Index = i }).ToList(); - foreach (var res in resList) + foreach (var res in alphanumEncTable.ToList().Select((x, i) => new { Chr = x, Index = i }).ToList()) { this.alphanumEncDict.Add(res.Chr, res.Index); } @@ -1277,7 +1256,6 @@ private void CreateAlignmentPatternTable() } } - private void CreateCapacityECCTable() { this.capacityECCTable = new List(); diff --git a/KeeTrayTOTP/Libraries/TOTPEncoder.cs b/KeeTrayTOTP/Libraries/TOTPEncoder.cs index 2642a1f..6238e79 100644 --- a/KeeTrayTOTP/Libraries/TOTPEncoder.cs +++ b/KeeTrayTOTP/Libraries/TOTPEncoder.cs @@ -3,7 +3,7 @@ namespace KeeTrayTOTP.Libraries { - class TOTPEncoder + internal static class TOTPEncoder { /// /// Character set for authenticator code @@ -13,25 +13,17 @@ class TOTPEncoder 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y'}; - - private static uint OTP2UInt(byte[] totp) - { - uint fullcode = BitConverter.ToUInt32(totp, 0) & 0x7fffffff; - - return fullcode; - } - public static readonly Func Rfc6238 = (byte[] bytes, int length) => { - uint fullcode = TOTPEncoder.OTP2UInt(bytes); - uint mask = (uint)Math.Pow(10, length); - return (fullcode % mask).ToString(new string('0', length)); + var fullcode = OTP2UInt(bytes); + var mask = (uint)Math.Pow(10, length); + return (fullcode % mask).ToString(new string('0', length)); }; public static readonly Func Steam = (byte[] bytes, int length) => { - uint fullcode = TOTPEncoder.OTP2UInt(bytes); + var fullcode = OTP2UInt(bytes); StringBuilder code = new StringBuilder(); for (var i = 0; i < length; i++) @@ -43,6 +35,9 @@ private static uint OTP2UInt(byte[] totp) return code.ToString(); }; - + private static uint OTP2UInt(byte[] totp) + { + return BitConverter.ToUInt32(totp, 0) & 0x7fffffff; + } } } diff --git a/KeeTrayTOTP/Libraries/TOTPProvider.cs b/KeeTrayTOTP/Libraries/TOTPProvider.cs index 0e83d26..edbd757 100644 --- a/KeeTrayTOTP/Libraries/TOTPProvider.cs +++ b/KeeTrayTOTP/Libraries/TOTPProvider.cs @@ -25,12 +25,12 @@ public int Duration } set { - if (!(value > 0)) + if (value <= 0) { throw new Exception("Invalid Duration."); //Throws an exception if the duration is invalid as the class cannot work without it. } - this._duration = value; //Defines variable from argument. + this._duration = value; } } @@ -54,67 +54,19 @@ public int Length this._length = value; //Defines variable from argument. } - } - - /// - /// TOTP Encoder. - /// - private Func _encoder; - public Func Encoder - { - get - { - return this._encoder; - } - set - { - this._encoder = value; //Defines variable from argument. - } - } + public Func Encoder { get; set; } /// /// Sets the time span that is used to match the server's UTC time to ensure accurate generation of Time-based One Time Passwords. /// - private TimeSpan _timeCorrection; - public TimeSpan TimeCorrection - { - get - { - return this._timeCorrection; - } - set - { - this._timeCorrection = value; //Defines variable from argument. - } - } + public TimeSpan TimeCorrection { get; set; } - private bool _timeCorrectionError; - public bool TimeCorrectionError - { - get - { - return this._timeCorrectionError; - } - } - - /// - /// Instanciates a new TOTP_Generator. - /// - /// Duration of generation of each totp, in seconds. - /// Length of the generated totp. - /// The output encoder. - /*public TOTPProvider(int initDuration, int initLength, Func initEncoder) - { - this.Duration = initDuration; - this.Length = initLength; - this.encoder = initEncoder; - this.TimeCorrection = TimeSpan.Zero; - }*/ + public bool TimeCorrectionError { get; private set; } /// - /// Instanciates a new TOTP_Generator. + /// Instantiate a new TOTP_Generator. /// /// Saved Settings. public TOTPProvider(string[] settings, ref TimeCorrectionCollection tcc) @@ -124,15 +76,15 @@ public TOTPProvider(string[] settings, ref TimeCorrectionCollection tcc) if (settings[1] == "S") { this._length = 5; - this._encoder = TOTPEncoder.Steam; + this.Encoder = TOTPEncoder.Steam; } else { this._length = Convert.ToInt16(settings[1]); - this._encoder = TOTPEncoder.Rfc6238; + this.Encoder = TOTPEncoder.Rfc6238; } - if(settings.Length > 2 && settings[2] != String.Empty) + if (settings.Length > 2 && settings[2] != String.Empty) { var tc = tcc[settings[2]]; @@ -143,15 +95,13 @@ public TOTPProvider(string[] settings, ref TimeCorrectionCollection tcc) else { this.TimeCorrection = TimeSpan.Zero; - this._timeCorrectionError = false; + this.TimeCorrectionError = false; } } else { this.TimeCorrection = TimeSpan.Zero; } - - } /// @@ -161,7 +111,7 @@ public DateTime Now { get { - return DateTime.UtcNow - _timeCorrection; //Computes current time minus time correction giving the corrected time. + return DateTime.UtcNow - TimeCorrection; // Computes current time minus time correction giving the corrected time. } } @@ -172,8 +122,8 @@ public int Timer { get { - var n = (_duration - (int)((Now - UnixEpoch).TotalSeconds % _duration)); //Computes the seconds left before counter incrementation. - return n == 0 ? _duration : n; //Returns timer value from 30 to 1. + var n = _duration - (int)((Now - UnixEpoch).TotalSeconds % _duration); // Computes the seconds left before counter incrementation. + return n == 0 ? _duration : n; // Returns timer value from 30 to 1. } } @@ -196,43 +146,17 @@ public long Counter /// Binary data. private byte[] GetBytes(ulong n) { - byte[] b = new byte[8]; //Math. - b[0] = (byte)(n >> 56); //Math. - b[1] = (byte)(n >> 48); //Math. - b[2] = (byte)(n >> 40); //Math. - b[3] = (byte)(n >> 32); //Math. - b[4] = (byte)(n >> 24); //Math. - b[5] = (byte)(n >> 16); //Math. - b[6] = (byte)(n >> 8); //Math. - b[7] = (byte)(n); //Math. - return b; - } - - /// - /// Generate a TOTP using provided binary data. - /// - /// Binary data. - /// Time-based One Time Password encoded byte array. - public byte[] Generate(byte[] key) - { - System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true); //Instanciates a new hash provider with a key. - byte[] hash = hmac.ComputeHash(GetBytes((ulong)Counter)); //Generates hash from key using counter. - hmac.Clear(); //Clear hash instance securing the key. - - /*int binary = //Math. - ((hash[offset] & 0x7f) << 24) //Math. - | ((hash[offset + 1] & 0xff) << 16) //Math. - | ((hash[offset + 2] & 0xff) << 8) //Math. - | (hash[offset + 3] & 0xff); //Math. - - int password = binary % (int)Math.Pow(10, length); //Math.*/ - - int offset = hash[hash.Length - 1] & 0x0f; //Math. - byte[] totp = { hash[offset + 3], hash[offset + 2], hash[offset + 1], hash[offset] }; - return totp; + byte[] b = new byte[8]; + b[0] = (byte)(n >> 56); + b[1] = (byte)(n >> 48); + b[2] = (byte)(n >> 40); + b[3] = (byte)(n >> 32); + b[4] = (byte)(n >> 24); + b[5] = (byte)(n >> 16); + b[6] = (byte)(n >> 8); + b[7] = (byte)(n); - /* - return password.ToString(new string('0', length)); //Math.*/ + return b; } /// @@ -242,20 +166,16 @@ public byte[] Generate(byte[] key) /// Time-based One Time Password encoded byte array. public string Generate(string key) { - byte[] bkey = Base32.Decode(key); - return this.GenerateByByte(bkey); + return this.GenerateByByte(Base32.Decode(key)); } - /// + /// /// Generate a TOTP using provided binary data. /// /// Binary data. /// Time-based One Time Password encoded byte array. public string GenerateByByte(byte[] key) { - - HMACSHA1 hmac = new HMACSHA1(key, true); //Instanciates a new hash provider with a key. - byte[] codeInterval = BitConverter.GetBytes((ulong)Counter); if (BitConverter.IsLittleEndian) @@ -263,19 +183,22 @@ public string GenerateByByte(byte[] key) Array.Reverse(codeInterval); } - byte[] hash = hmac.ComputeHash(codeInterval); //Generates hash from key using counter. - hmac.Clear(); //Clear hash instance securing the key. - int start = hash[hash.Length - 1] & 0xf; - byte[] totp = new byte[4]; - - Array.Copy(hash, start, totp, 0, 4); - if (BitConverter.IsLittleEndian) + using (var hmac = new HMACSHA1(key, true)) { - Array.Reverse(totp); - } + byte[] hash = hmac.ComputeHash(codeInterval); //Generates hash from key using counter. + hmac.Clear(); //Clear hash instance securing the key. - return this._encoder(totp, _length); - } + int start = hash[hash.Length - 1] & 0xf; + byte[] totp = new byte[4]; + + Array.Copy(hash, start, totp, 0, 4); + if (BitConverter.IsLittleEndian) + { + Array.Reverse(totp); + } + return this.Encoder(totp, _length); + } + } } } \ No newline at end of file diff --git a/KeeTrayTOTP/Libraries/TimeCorrectionProvider.cs b/KeeTrayTOTP/Libraries/TimeCorrectionProvider.cs index 646ff5d..fc2dbce 100644 --- a/KeeTrayTOTP/Libraries/TimeCorrectionProvider.cs +++ b/KeeTrayTOTP/Libraries/TimeCorrectionProvider.cs @@ -49,7 +49,7 @@ public class TimeCorrectionProvider /// public DateTime LastUpdateDateTime { get { return _lastUpdateDateTime; } } - private bool _lastUpdateSucceded = false; + private bool _lastUpdateSucceded; /// /// Returns true if the last check for time correction was successful. /// diff --git a/KeeTrayTOTP/SetupTOTP.cs b/KeeTrayTOTP/SetupTOTP.cs index 6985a54..5d2e3af 100644 --- a/KeeTrayTOTP/SetupTOTP.cs +++ b/KeeTrayTOTP/SetupTOTP.cs @@ -4,7 +4,6 @@ using KeePassLib; using KeePassLib.Security; - namespace KeeTrayTOTP { public partial class SetupTOTP : Form @@ -82,7 +81,6 @@ private void SetupTOTP_Load(object sender, EventArgs e) ErrorProviderSetup.SetError(NumericIntervalSetup, string.Empty); ErrorProviderSetup.SetError(RadioButtonLength8Setup, string.Empty); ErrorProviderSetup.SetError(ComboBoxTimeCorrectionSetup, string.Empty); - } private void CheckBoxSeedVisibility_CheckedChanged(object sender, EventArgs e) diff --git a/KeeTrayTOTP/ShowQR.cs b/KeeTrayTOTP/ShowQR.cs index 7918ae9..444244b 100644 --- a/KeeTrayTOTP/ShowQR.cs +++ b/KeeTrayTOTP/ShowQR.cs @@ -30,9 +30,7 @@ private void GenerateQRCode() { var qrCodeData = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q); var qrCode = new QRCode(qrCodeData); - var qrCodeImage = qrCode.GetGraphic(6); - - QROutputPicture.Image = qrCodeImage; + QROutputPicture.Image = qrCode.GetGraphic(6); } } diff --git a/KeeTrayTOTP/TrayTOTP_CustomColumn.cs b/KeeTrayTOTP/TrayTOTP_CustomColumn.cs index 776d277..75540c9 100644 --- a/KeeTrayTOTP/TrayTOTP_CustomColumn.cs +++ b/KeeTrayTOTP/TrayTOTP_CustomColumn.cs @@ -9,126 +9,119 @@ namespace KeeTrayTOTP { - /// - /// Main Plugin Class - /// - public sealed partial class KeeTrayTOTPExt + internal class TrayTOTP_CustomColumn : ColumnProvider { - internal class TrayTOTP_CustomColumn : ColumnProvider + /// + /// Reference to the plugin host for access to KeePass functions. + /// + private readonly IPluginHost _pluginHost; + + /// + /// Reference to the main plugin class. + /// + private readonly KeeTrayTOTPExt _plugin; + + /// + /// Provides support to add a custom column to KeePass, in this case the TOTP Provider Column. + /// + /// Handle to the plugin class. + internal TrayTOTP_CustomColumn(KeeTrayTOTPExt plugin) { - /// - /// Reference to the plugin host for access to KeePass functions. - /// - private readonly IPluginHost _pluginHost; - - /// - /// Reference to the main plugin class. - /// - private readonly KeeTrayTOTPExt _plugin; - - /// - /// Provides support to add a custom column to KeePass, in this case the TOTP Provider Column. - /// - /// Handle to the plugin class. - internal TrayTOTP_CustomColumn(KeeTrayTOTPExt plugin) - { - _plugin = plugin; - _pluginHost = _plugin.PluginHost; - } + _plugin = plugin; + _pluginHost = _plugin.PluginHost; + } + + /// + /// Column Names, in the case this provider handles more than one column. + /// + private readonly string[] _columnName = new[] { Localization.Strings.TOTP }; + + /// + /// Informs Keepass of the Column Names, in the case this provider handles more than one column. + /// + public override string[] ColumnNames + { + get { return _columnName; } + } - /// - /// Column Names, in the case this provider handles more than one column. - /// - private readonly string[] _columnName = new[] {Localization.Strings.TOTP}; + /// + /// Informs KeePass what alignment the column's data should have. + /// + public override HorizontalAlignment TextAlign + { + get { return HorizontalAlignment.Left; } + } - /// - /// Informs Keepass of the Column Names, in the case this provider handles more than one column. - /// - public override string[] ColumnNames + /// + /// Tells KeePass what to display in the column. + /// + /// + /// + /// String displayed in the columns. + public override string GetCellData(string columnName, PwEntry pe) + { + if (columnName == null) { - get { return _columnName; } + throw new ArgumentNullException("columnName"); } - /// - /// Informs KeePass what alignment the column's data should have. - /// - public override HorizontalAlignment TextAlign + if (pe == null) { - get { return HorizontalAlignment.Left; } + throw new ArgumentNullException("pe"); } - /// - /// Tells KeePass what to display in the column. - /// - /// - /// - /// String displayed in the columns. - public override string GetCellData(string columnName, PwEntry pe) + if (_plugin.SettingsCheck(pe) && _plugin.SeedCheck(pe)) { - if (columnName == null) + bool validInterval; + bool validLength; + bool validUrl; + if (_plugin.SettingsValidate(pe, out validInterval, out validLength, out validUrl)) { - throw new ArgumentNullException("columnName"); - } + string[] settings = _plugin.SettingsGet(pe); - if (pe == null) - { - throw new ArgumentNullException("pe"); - } + TOTPProvider totpGenerator = new TOTPProvider(settings, ref _plugin.TimeCorrections); - if (_plugin.SettingsCheck(pe) && _plugin.SeedCheck(pe)) - { - bool validInterval; - bool validLength; - bool validUrl; - if (_plugin.SettingsValidate(pe, out validInterval, out validLength, out validUrl)) + if (_plugin.SeedValidate(pe)) { - string[] settings = _plugin.SettingsGet(pe); - - TOTPProvider totpGenerator = new TOTPProvider(settings, ref _plugin.TimeCorrections); - - if (_plugin.SeedValidate(pe)) - { - return totpGenerator.GenerateByByte( - Base32.Decode(_plugin.SeedGet(pe).ReadString().ExtWithoutSpaces())) + (_pluginHost.CustomConfig.GetBool(setname_bool_TOTPColumnTimer_Visible, true) ? totpGenerator.Timer.ToString().ExtWithParenthesis().ExtWithSpaceBefore() : string.Empty); - } - return Localization.Strings.ErrorBadSeed; + return totpGenerator.GenerateByByte(Base32.Decode(_plugin.SeedGet(pe).ReadString().ExtWithoutSpaces())) + (_pluginHost.CustomConfig.GetBool(KeeTrayTOTPExt.setname_bool_TOTPColumnTimer_Visible, true) ? totpGenerator.Timer.ToString().ExtWithParenthesis().ExtWithSpaceBefore() : string.Empty); } - return Localization.Strings.ErrorBadSettings; + return Localization.Strings.ErrorBadSeed; } - return (_plugin.SettingsCheck(pe) || _plugin.SeedCheck(pe) ? Localization.Strings.ErrorStorage : string.Empty); + return Localization.Strings.ErrorBadSettings; } + return (_plugin.SettingsCheck(pe) || _plugin.SeedCheck(pe) ? Localization.Strings.ErrorStorage : string.Empty); + } - /// - /// Informs KeePass if PerformCellAction must be called when the cell is double clicked. - /// - /// Column Name. - /// - public override bool SupportsCellAction(string columnName) + /// + /// Informs KeePass if PerformCellAction must be called when the cell is double clicked. + /// + /// Column Name. + /// + public override bool SupportsCellAction(string columnName) + { + if (columnName == null) { - if (columnName == null) - { - throw new ArgumentNullException("columnName"); - } - - return true; + throw new ArgumentNullException("columnName"); } - /// - /// Happens when a cell of the column is double-clicked. - /// - /// Column's name. - /// Entry associated with the clicked cell. - public override void PerformCellAction(string columnName, PwEntry pe) + return true; + } + + /// + /// Happens when a cell of the column is double-clicked. + /// + /// Column's name. + /// Entry associated with the clicked cell. + public override void PerformCellAction(string columnName, PwEntry pe) + { + if (columnName == null) { - if (columnName == null) - { - throw new ArgumentNullException("columnName"); - } + throw new ArgumentNullException("columnName"); + } - if (_pluginHost.CustomConfig.GetBool(setname_bool_TOTPColumnCopy_Enable, true)) - { - _plugin.TOTPCopyToClipboard(pe); - } + if (_pluginHost.CustomConfig.GetBool(KeeTrayTOTPExt.setname_bool_TOTPColumnCopy_Enable, true)) + { + _plugin.TOTPCopyToClipboard(pe); } } } diff --git a/KeeTrayTOTP/TrayTOTP_Extensions.cs b/KeeTrayTOTP/TrayTOTP_Extensions.cs index a62d315..f02c8d9 100644 --- a/KeeTrayTOTP/TrayTOTP_Extensions.cs +++ b/KeeTrayTOTP/TrayTOTP_Extensions.cs @@ -85,18 +85,6 @@ internal static string ExtWithout(this string extension, string chars) return extension; } - /// - /// Converts the control's tag to text and splits it. - /// - /// Current string. - /// Split index. - /// Split seperators. - /// - internal static string ExtSplitFromTag(this System.Windows.Forms.Control extension, int index = 0, char seperator = ';') - { - return extension.Tag.ToString().ExtSplit(index, seperator); - } - /// /// Splits the string and returns specified substring. /// diff --git a/KeeTrayTOTP/TrayTOTP_Plugin.cs b/KeeTrayTOTP/TrayTOTP_Plugin.cs index 82583c4..2c22364 100644 --- a/KeeTrayTOTP/TrayTOTP_Plugin.cs +++ b/KeeTrayTOTP/TrayTOTP_Plugin.cs @@ -23,12 +23,12 @@ namespace KeeTrayTOTP /// /// Main Plugin Class /// - public sealed partial class KeeTrayTOTPExt : Plugin + public sealed class KeeTrayTOTPExt : Plugin { /// /// Plugin host Global Reference for access to KeePass functions. /// - internal IPluginHost PluginHost = null; + internal IPluginHost PluginHost; /// /// Tray TOTP Support Url @@ -94,47 +94,35 @@ public sealed partial class KeeTrayTOTPExt : Plugin /// /// Notify Icon Context Menu Separator. /// - private ToolStripSeparator _niMenuSeperator = null; + private ToolStripSeparator _niMenuSeperator; /// /// Entries Column TOTP. /// - private TrayTOTP_CustomColumn _liColumnTotp = null; + private TrayTOTP_CustomColumn _liColumnTotp; /// /// Entry List Column Count. /// - private int _liColumnsCount = 0; + private int _liColumnsCount; /// /// Entry List Column TOTP visibility. /// - private bool _liColumnTotpVisible = false; + private bool _liColumnTotpVisible; /// /// Entry Groups last selected group. /// - private PwGroup _liGroupsPreviousSelected = null; + private PwGroup _liGroupsPreviousSelected; /// /// Entry Column TOTP has TOTPs. /// - private bool _liColumnTotpContains = false; + private bool _liColumnTotpContains; /// /// Entries Refresh Timer. /// private Timer _liRefreshTimer = new Timer(); - /// - /// Entries Refresh Timer. - /// - internal int LiRefreshTimerInterval - { - set - { - _liRefreshTimer.Interval = value; - _liRefreshTimer.Enabled = true; - } - } - /// /// Entries Refresh Timer Previous Counter to Prevent Useless Refresh. /// @@ -209,8 +197,7 @@ public override ToolStripMenuItem GetMenuItem(PluginMenuType type) enMenuCopyTotp.Enabled = false; enMenuSetupTotp.Enabled = false; - bool boolCopy = PluginHost.CustomConfig.GetBool(setname_bool_EntryContextCopy_Visible, true); - enMenuCopyTotp.Visible = boolCopy; + enMenuCopyTotp.Visible = PluginHost.CustomConfig.GetBool(setname_bool_EntryContextCopy_Visible, true); if (PluginHost.MainWindow.GetSelectedEntriesCount() == 1) { @@ -227,8 +214,7 @@ public override ToolStripMenuItem GetMenuItem(PluginMenuType type) enMenuSetupTotp.Enabled = true; } - bool boolSetup = PluginHost.CustomConfig.GetBool(setname_bool_EntryContextSetup_Visible, true); - enMenuSetupTotp.Visible = boolSetup; + enMenuSetupTotp.Visible = PluginHost.CustomConfig.GetBool(setname_bool_EntryContextSetup_Visible, true); }; enMenuTrayTotp.DropDownClosed += delegate (object sender, EventArgs e) @@ -712,7 +698,8 @@ internal bool SettingsValidate(PwEntry pe) { bool validInterval; bool validLength; - bool validUrl; //Dummies + bool validUrl; + return SettingsValidate(pe, out validInterval, out validLength, out validUrl); } @@ -725,6 +712,7 @@ internal bool SettingsValidate(PwEntry pe) internal bool SettingsValidate(PwEntry pe, out bool isUrlValid) { bool validInterval; bool validLength; //Dummies + return SettingsValidate(pe, out validInterval, out validLength, out isUrlValid); } @@ -767,7 +755,7 @@ private static bool UrlIsValid(string[] settings) return false; } - return settings[2].StartsWith("http://") || settings[2].StartsWith("https://"); + return settings[2].StartsWith("http://") || settings[2].StartsWith("https://"); } private bool LengthIsValid(string[] settings) @@ -862,7 +850,7 @@ internal ProtectedString SeedGet(PwEntry pe) /// Copies the specified entry's generated TOTP to the clipboard using the KeePass's clipboard function. /// /// Password Entry. - private void TOTPCopyToClipboard(PwEntry pe) + internal void TOTPCopyToClipboard(PwEntry pe) { if (SettingsCheck(pe) && SeedCheck(pe)) { diff --git a/KeeTrayTOTP/TrayTOTP_TimeCorrectionCollection.cs b/KeeTrayTOTP/TrayTOTP_TimeCorrectionCollection.cs index 04460dd..650579a 100644 --- a/KeeTrayTOTP/TrayTOTP_TimeCorrectionCollection.cs +++ b/KeeTrayTOTP/TrayTOTP_TimeCorrectionCollection.cs @@ -10,7 +10,7 @@ namespace KeeTrayTOTP /// /// Time_Correction Collection. /// - public class TimeCorrectionCollection : IEnumerable + public class TimeCorrectionCollection { /// /// Time Correction List. @@ -64,35 +64,6 @@ internal TimeCorrectionCollection(bool enable = true) _timeCorrections = new List(); } - /// - /// Populates the Time Correction Collection with the URLs in the specified string. - /// - /// URLs. - internal void AddRangeFromString(string urLs) - { - foreach (var url in urLs.Split(';')) - { - //Validating that url is not null. - if (url != String.Empty) - { - //Validating that this server is not already checked. - bool next = false; - foreach (var timeC in _timeCorrections) - { - if (timeC.Url == url) - { - next = true; - } - } - //Adding server to time correction collection. - if (!next) - { - _timeCorrections.Add(new TimeCorrectionProvider(url, _enable)); - } - } - } - } - /// /// Populates the Time Correction Collection with the URL list specified. /// @@ -231,23 +202,5 @@ internal string ToSetting() } return @return.TrimEnd(';'); } - - /// - /// Support the enumeration of the collection to handle [foreach (var VARIABLE in...]. - /// - /// Time Correction List Enumerator. - public IEnumerator GetEnumerator() - { - return _timeCorrections.GetEnumerator(); - } - - /// - /// Support the enumeration of the collection to handle [foreach (TimeCorrection_Provider VARIABLE in...]. - /// - /// Time Correction List Enumerator. - IEnumerator IEnumerable.GetEnumerator() - { - return _timeCorrections.GetEnumerator(); - } } } \ No newline at end of file