Skip to content

Commit

Permalink
Refactor code (#96)
Browse files Browse the repository at this point in the history
Go through the code and cleanup as I go.

* Removed dead code
* Whitespace / newlines
* Prefer var
* Prefer not initializing fields explicitly
* Seal classes
* Use auto properties
* Dispose of IDisposable instances
  • Loading branch information
robinvanpoppel committed Apr 11, 2020
1 parent 88e42ca commit e705a6f
Show file tree
Hide file tree
Showing 15 changed files with 173 additions and 364 deletions.
2 changes: 1 addition & 1 deletion KeeTrayTOTP.Tests/ExpiryTests.cs
Expand Up @@ -5,7 +5,7 @@
namespace KeeTrayTOTP.Tests
{
[TestClass]
public class ExpiryTests
public class ExpiryTests
{
[TestMethod]
public void IsExpired_ShouldReturnTrue_WhenExpiresIsTrueAndExpiryTimeInThePast()
Expand Down
2 changes: 1 addition & 1 deletion KeeTrayTOTP/FormHelp.cs
Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion KeeTrayTOTP/FormSettings.cs
Expand Up @@ -16,7 +16,7 @@ internal partial class FormSettings : Form
/// <param name="sender"></param>
/// <param name="e"></param>
private delegate void SafeCallDelegate(object sender, DoWorkEventArgs e);

/// <summary>
/// Plugin Host.
/// </summary>
Expand Down
7 changes: 2 additions & 5 deletions KeeTrayTOTP/Libraries/QRCoder/QRCode.cs
Expand Up @@ -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()
{
Expand Down Expand Up @@ -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)
{
Expand Down
20 changes: 9 additions & 11 deletions KeeTrayTOTP/Libraries/QRCoder/QRCodeData.cs
Expand Up @@ -36,7 +36,7 @@ namespace QRCoder
public class QRCodeData : IDisposable
{
public List<BitArray> ModuleMatrix { get; set; }

public QRCodeData(int version)
{
this.Version = version;
Expand All @@ -63,8 +63,8 @@ public QRCodeData(byte[] rawData, Compression compressMode)
Stream4Methods.CopyTo(dstream, output);
}
bytes = new List<byte>(output.ToArray());
}
}
}
}
}
else if (compressMode.Equals(Compression.GZip))
{
Expand Down Expand Up @@ -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<BitArray>();
for (int y = 0; y < sideLen; y++)
Expand All @@ -112,16 +112,15 @@ public QRCodeData(byte[] rawData, Compression compressMode)
this.ModuleMatrix[y][x] = modules.Dequeue();
}
}

}

public byte[] GetRawData(Compression compressMode)
{
var bytes = new List<byte>();

//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);

Expand Down Expand Up @@ -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;
Expand All @@ -188,7 +187,6 @@ public void Dispose()
{
this.ModuleMatrix = null;
this.Version = 0;

}

public enum Compression
Expand Down
30 changes: 4 additions & 26 deletions KeeTrayTOTP/Libraries/QRCoder/QRCodeGenerator.cs
Expand Up @@ -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++)
Expand All @@ -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)
Expand All @@ -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<Rectangle>();
Expand All @@ -196,7 +193,6 @@ public QRCodeData CreateQrCode(string plainText, ECCLevel eccLevel, bool forceUt
ModulePlacer.PlaceVersion(ref qr, versionString);
}


ModulePlacer.AddQuietZone(ref qr);
return qr;
}
Expand Down Expand Up @@ -328,17 +324,14 @@ public static void PlaceFormat(ref QRCodeData qrCode, string formatStr)
}
}


public static int MaskCode(ref QRCodeData qrCode, int version, ref List<Rectangle> blockedModules, ECCLevel eccLevel)
{
var patternName = string.Empty;
var patternScore = 0;

var size = qrCode.ModuleMatrix.Count;

var methods = typeof(MaskPattern).GetMethods();

foreach (var pattern in methods)
foreach (var pattern in typeof(MaskPattern).GetMethods())
{
if (pattern.Name.Length != 8 || pattern.Name.Substring(0, 7) != "Pattern")
{
Expand All @@ -352,7 +345,6 @@ public static int MaskCode(ref QRCodeData qrCode, int version, ref List<Rectangl
{
qrTemp.ModuleMatrix[y][x] = qrCode.ModuleMatrix[y][x];
}

}

var patternNameFragment = pattern.Name.Substring(7, 1);
Expand Down Expand Up @@ -398,7 +390,6 @@ public static int MaskCode(ref QRCodeData qrCode, int version, ref List<Rectangl
return Convert.ToInt32(patternMethod.Name.Substring(patternMethod.Name.Length - 1, 1)) - 1;
}


public static void PlaceDataWords(ref QRCodeData qrCode, string data, ref List<Rectangle> blockedModules)
{
var size = qrCode.ModuleMatrix.Count;
Expand Down Expand Up @@ -654,7 +645,6 @@ public static int Score(ref QRCodeData qrCode)

lastValRow = qrCode.ModuleMatrix[y][x];


if (qrCode.ModuleMatrix[x][y] == lastValColumn)
{
modInColumn++;
Expand All @@ -677,7 +667,6 @@ public static int Score(ref QRCodeData qrCode)
}
}


//Penalty 2
for (var y = 0; y < size - 1; y++)
{
Expand Down Expand Up @@ -772,7 +761,6 @@ public static int Score(ref QRCodeData qrCode)
return score1 + score2 + score3 + score4;
}
}

}

private List<string> CalculateECCWords(string bitString, ECCInfo eccInfo)
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -893,7 +880,6 @@ private Polynom CalculateMessagePolynom(string bitString)
return messagePol;
}


private Polynom CalculateGeneratorPolynom(int numEccWords)
{
var generatorPolynom = new Polynom();
Expand Down Expand Up @@ -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)
{
Expand All @@ -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)
{
Expand All @@ -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);
}
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand All @@ -1184,7 +1165,6 @@ private Polynom MultiplyGeneratorPolynomByLeadterm(Polynom genPolynom, PolynomIt
return resultPolynom;
}


private Polynom MultiplyAlphaPolynoms(Polynom polynomBase, Polynom polynomMultiplier)
{
var resultPolynom = new Polynom();
Expand Down Expand Up @@ -1236,8 +1216,7 @@ private void CreateAlphanumEncDict()
{
this.alphanumEncDict = new Dictionary<char, int>();
//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);
}
Expand Down Expand Up @@ -1277,7 +1256,6 @@ private void CreateAlignmentPatternTable()
}
}


private void CreateCapacityECCTable()
{
this.capacityECCTable = new List<ECCInfo>();
Expand Down
23 changes: 9 additions & 14 deletions KeeTrayTOTP/Libraries/TOTPEncoder.cs
Expand Up @@ -3,7 +3,7 @@

namespace KeeTrayTOTP.Libraries
{
class TOTPEncoder
internal static class TOTPEncoder
{
/// <summary>
/// Character set for authenticator code
Expand All @@ -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<byte[], int, string> 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<byte[], int, string> 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++)
Expand All @@ -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;
}
}
}

0 comments on commit e705a6f

Please sign in to comment.