Skip to content

Commit

Permalink
More LGTM suggested improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
jbtule committed Sep 18, 2019
1 parent 821ed32 commit 8e0533d
Show file tree
Hide file tree
Showing 17 changed files with 95 additions and 69 deletions.
3 changes: 2 additions & 1 deletion Keyczar/Keyczar.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
<s:Boolean x:Key="/Default/UserDictionary/Words/=lgtm/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=pkcs/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=priv/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=testdata/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
<s:Boolean x:Key="/Default/UserDictionary/Words/=testdata/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Tuley/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
6 changes: 5 additions & 1 deletion Keyczar/Keyczar/AttachedSigner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,11 @@ protected override void PadSignature(byte[] signature, Stream outputStream, obje
var position = padData.Item2;
var input = padData.Item3;

var key = GetPrimaryKey() as ISignerKey;
if (!(GetPrimaryKey() is ISignerKey key))
{
throw new InvalidOperationException("Signing key required for signing.");
}

outputStream.Write(KeyczarConst.FormatBytes, 0, KeyczarConst.FormatBytes.Length);
outputStream.Write(key.GetKeyHash(), 0, KeyczarConst.KeyHashLength);

Expand Down
3 changes: 0 additions & 3 deletions Keyczar/Keyczar/Compat/ImportedKeySet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,6 @@ public virtual ImportedKeySet Pkcs12Keys(KeyPurpose purpose, Stream input, Func<
{
var keyStore = new Pkcs12Store(input, password.Prompt().ToCharArray());
var keys = new List<Key>();
var kind = KeyKind.Private;
foreach (string n in keyStore.Aliases)
{
if (keyStore.IsKeyEntry(n))
Expand All @@ -355,8 +354,6 @@ public virtual ImportedKeySet Pkcs12Keys(KeyPurpose purpose, Stream input, Func<
}
if (!keys.Any())
{
kind = KeyKind.Public;

foreach (string n in keyStore.Aliases)
{
if (keyStore.IsCertificateEntry(n))
Expand Down
8 changes: 4 additions & 4 deletions Keyczar/Keyczar/Crypto/DsaPublicKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,15 @@ internal IDigest GetDigest()
/// <returns></returns>
public VerifyingStream GetVerifyingStream(KeyczarBase keyczar)
{
var tSigner = new DsaSigner();
tSigner.Init(forSigning: false, parameters: new DsaPublicKeyParameters(Y.ToBouncyBigInteger(),
var signer = new DsaSigner();
signer.Init(forSigning: false, parameters: new DsaPublicKeyParameters(Y.ToBouncyBigInteger(),
new DsaParameters(
P.ToBouncyBigInteger(),
Q.ToBouncyBigInteger(),
G.ToBouncyBigInteger())));
var digest = GetDigest();
var signer = new DsaDigestSigner(tSigner, digest);
return new DigestStream(new DsaDigestSigner(tSigner, digest), sigRepair: sig =>{
var digestSigner = new DsaDigestSigner(signer, digest);
return new DigestStream(digestSigner, sigRepair: sig =>{
if (!keyczar.Config.StrictDsaVerification)
{
return Utility.RemoveJunkFronAnsiObj(sig);
Expand Down
3 changes: 0 additions & 3 deletions Keyczar/Keyczar/Crypto/Streams/AsymmetricStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,6 @@ private void Init()
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
}
_cipher.Reset();
_cipher = null;
_output.Flush();
Expand Down
2 changes: 1 addition & 1 deletion Keyczar/Keyczar/KeySet/Metadata/KeyMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public KeyMetadata(KeyMetadata metadata)
Encrypted = metadata.Encrypted;
Versions = metadata.Versions.Select(it => new KeyVersion(it)).ToList();
#pragma warning disable 618
KeyType = metadata?.KeyType;
KeyType = metadata.KeyType;
#pragma warning restore 618
OriginallyOfficial = metadata.OriginallyOfficial;
Kind = metadata.Kind;
Expand Down
10 changes: 4 additions & 6 deletions Keyczar/Keyczar/KeySet/Metadata/KeyType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,10 @@ static KeyType()
RsaPriv.KeySizes<RsaPrivateKey>(2048, 4096).WeakSizes(1024).IsAsymmetric().DefineSpec();
RsaPub.KeySizes<RsaPublicKey>(2048, 4096).WeakSizes(1024).IsAsymmetric().IsPublic().DefineSpec();

#pragma warning disable 219
KeyType see;
#pragma warning restore 219
see = UnofficialKeyType.AesAead;
see = UnofficialKeyType.RSAPrivSign;
see = UnofficialKeyType.RSAPubSign;
var dummy = UnofficialKeyType.AesAead;// inference first run construction - lgtm [cs/useless-assignment-to-local]
dummy = UnofficialKeyType.RSAPrivSign;// inference first run construction - lgtm [cs/useless-assignment-to-local]
dummy = UnofficialKeyType.RSAPubSign; // inference first run construction - lgtm [cs/useless-assignment-to-local]

}

private static readonly IDictionary<string, KeyTypeSpec> _specs = new Dictionary<string, KeyTypeSpec>();
Expand Down
26 changes: 18 additions & 8 deletions Keyczar/Keyczar/SessionCrypter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -256,16 +256,19 @@ public void Decrypt(Stream input, Stream output, long inputLength = -1)
{
throw new InvalidCryptoDataException("Can't decrypted, when in signer is provided");
}
var finalinput = input;
var finalInput = input;
MemoryStream extraStep = null;
if (_working.Value._verifier != null)
{
finalinput = new MemoryStream();
_working.Value._verifier.VerifiedMessage(input, finalinput, hidden: _working.Value._nonce, inputLength: inputLength);
extraStep = new MemoryStream();
finalInput = extraStep;
_working.Value._verifier.VerifiedMessage(input, finalInput, hidden: _working.Value._nonce, inputLength: inputLength);
inputLength = -1;
finalinput.Seek(0, SeekOrigin.Begin);
finalInput.Seek(0, SeekOrigin.Begin);
}
_working.Value._crypter.Compression = Compression;
_working.Value._crypter.Decrypt(finalinput, output, inputLength);
_working.Value._crypter.Decrypt(finalInput, output, inputLength);
extraStep?.Dispose();
}

/// <summary>
Expand Down Expand Up @@ -317,17 +320,20 @@ public void Encrypt(Stream input, Stream output, long inputLength = -1)
}
_working.Value._crypter.Compression = Compression;

Stream finaloutput = output;
var finalOutput = output;
MemoryStream extraStep = null;
if (_working.Value._signer != null)
{
output = new MemoryStream();
extraStep = new MemoryStream();
output = extraStep;
}
_working.Value._crypter.Encrypt(input, output, inputLength);
if (_working.Value._signer != null)
{
output.Seek(0, SeekOrigin.Begin);
_working.Value._signer.Sign(output, finaloutput, hidden: _working.Value._nonce);
_working.Value._signer.Sign(output, finalOutput, hidden: _working.Value._nonce);
}
extraStep?.Dispose();
}


Expand Down Expand Up @@ -459,6 +465,10 @@ public class SimpleAesHmacSha1KeyPacker : ISessionKeyPacker
public byte[] Pack(Key key, KeyczarConfig config)
{
var aesKey = key as AesKey;
if (aesKey is null)
{
throw new InvalidKeySetException("Can only pack AesKey keys.");
}
var inputArrays = new byte[][] {aesKey.AesKeyBytes, aesKey.HmacKey.HmacKeyBytes};
// Count an int for each input array
int outputSize = (1 + inputArrays.Length)*4;
Expand Down
17 changes: 14 additions & 3 deletions Keyczar/Keyczar/Signer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,15 @@ public Signer(IKeySet keySet) : base(keySet)
{
if (keySet.Metadata.Purpose != KeyPurpose.SignAndVerify)
{
throw new InvalidKeySetException("This key set can not be used for signing and verifying.");
throw MakeInvalidKeySetTypeException();
}
}

private static InvalidKeySetException MakeInvalidKeySetTypeException()
{
return new InvalidKeySetException("This key set can not be used for signing and verifying.");
}

/// <summary>
/// Signs the specified raw data.
/// </summary>
Expand Down Expand Up @@ -99,7 +104,10 @@ public byte[] Sign(Stream input, long inputLength=-1)
protected void Sign(Stream input, Stream outstream, object prefixData, object postfixData, object signatureData, long inputLength)
{
var stopLength = inputLength < 0 ? long.MaxValue : input.Position + inputLength;
var key = GetPrimaryKey() as ISignerKey;
if (!(GetPrimaryKey() is ISignerKey key))
{
throw MakeInvalidKeySetTypeException();
}
using (var reader = new NondestructiveBinaryReader(input))
{
using (var signingStream = key.GetSigningStream(this))
Expand Down Expand Up @@ -149,7 +157,10 @@ protected virtual void PostfixDataSign(HashingStream signingStream, object extra
/// <returns></returns>
protected virtual void PadSignature(byte[] signature, Stream outputStream, object extra)
{
var key = GetPrimaryKey() as ISignerKey;
if (!(GetPrimaryKey() is ISignerKey key))
{
throw new InvalidOperationException("Signing key required for signing.");
}
outputStream.Write(KeyczarConst.FormatBytes,0,KeyczarConst.FormatBytes.Length);
outputStream.Write(key.GetKeyHash(),0,KeyczarConst.KeyHashLength);
outputStream.Write(signature,0,signature.Length);
Expand Down
3 changes: 2 additions & 1 deletion Keyczar/Keyczar/Unofficial/BsonSessionKeyPacker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,9 @@ public byte[] Pack(Key key, KeyczarConfig config)
public Key Unpack(byte[] data, KeyczarConfig config)
{
using (var input = new MemoryStream(data))
using (var reader = new BsonDataReader(input))
{
var reader = new BsonDataReader(input);

var val = JToken.ReadFrom(reader);
var keyType = (KeyType) (string) val["type"];
var keyString = val["key"].ToString();
Expand Down
2 changes: 1 addition & 1 deletion Keyczar/Keyczar/Unofficial/HmacSha2Key.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ protected int HashLengthForDigest(DigestAlg digestAlg)
{
switch (digestAlg)
{
case DigestAlg alg when digestAlg == DigestAlg.Sha256:
case DigestAlg alg when alg == DigestAlg.Sha256:
return 256 / 8;
case DigestAlg alg when alg == DigestAlg.Sha384:
return 384 / 8;
Expand Down
3 changes: 1 addition & 2 deletions Keyczar/Keyczar/Util/Secure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ public static class Secure
/// <returns></returns>
public static T SafeDispose<T>(this T disposable) where T : class, IDisposable
{
if (disposable != null)
disposable.Dispose();
disposable?.Dispose();
return null;
}

Expand Down
18 changes: 10 additions & 8 deletions Keyczar/Keyczar/Util/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ public static class Utility
public static byte[] RemoveJunkFronAnsiObj(byte[] data)
{
using (var input = new MemoryStream(data))
{
var asn1 = new Asn1InputStream(input, data.Length);
using(var asn1 = new Asn1InputStream(input, data.Length))
{
var result = asn1.ReadObject();
return result.GetDerEncoded();
}
}

/// <summary>
/// Resets the stream poisition when Closed or Disposed.
/// Resets the stream position when Closed or Disposed.
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns></returns>
Expand All @@ -55,7 +55,7 @@ public static NondestructiveStreamReset ResetStreamWhenFinished(Stream stream)


/// <summary>
/// Copies string/object dictionary to the destnation objects properties.
/// Copies string/object dictionary to the destination objects properties.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="destination">The dest.</param>
Expand Down Expand Up @@ -110,10 +110,12 @@ public static byte[] ToBson(this object value)
using (var output = new MemoryStream())
{
var serializer = new JsonSerializer {ContractResolver = new CamelCasePropertyNamesContractResolver(),};
var writer = new BsonDataWriter(output);
serializer.Serialize(writer, value);
output.Flush();
return output.ToArray();
using (var writer = new BsonDataWriter(output))
{
serializer.Serialize(writer, value);
output.Flush();
return output.ToArray();
}
}
}

Expand Down
12 changes: 8 additions & 4 deletions Keyczar/Keyczar/Util/WebBase64Converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,13 +174,15 @@ public static char[] Encode(byte[] input)
int buffer = (0xFF & input[inPos++]) << 16;
if (remainder == 2)
{
buffer |= (0xFF & input[inPos++]) << 8;
// ReSharper disable once RedundantAssignment
buffer |= (0xFF & input[inPos++]) << 8; //might be unnecessary but is more readable - lgtm [cs/useless-assignment-to-local]
}
outChar[outPos++] = ALPHABET[(buffer >> 18) & 0x3F];
outChar[outPos++] = ALPHABET[(buffer >> 12) & 0x3F];
if (remainder == 2)
{
outChar[outPos++] = ALPHABET[(buffer >> 6) & 0x3F];
// ReSharper disable once RedundantAssignment
outChar[outPos++] = ALPHABET[(buffer >> 6) & 0x3F]; //might be unnecessary but is more readable - lgtm [cs/useless-assignment-to-local]
}
}
return outChar;
Expand Down Expand Up @@ -254,11 +256,13 @@ public static Byte[] Decode(char[] input)
switch (buffCount)
{
case 2:
outChar[outPos++] = (byte) (buffer >> 4);
// ReSharper disable once RedundantAssignment
outChar[outPos++] = (byte) (buffer >> 4); //might be unnecessary but is more readable - lgtm [cs/useless-assignment-to-local]
break;
case 3:
outChar[outPos++] = (byte) (buffer >> 10);
outChar[outPos++] = (byte) (buffer >> 2);
// ReSharper disable once RedundantAssignment
outChar[outPos++] = (byte) (buffer >> 2); //might be unnecessary but is more readable - lgtm [cs/useless-assignment-to-local]
break;
}

Expand Down
2 changes: 1 addition & 1 deletion Keyczar/KeyczarTest/Support/DotNetSymmetricStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ protected override void Dispose(bool disposing)
if (disposing)
{
var alg = _algorithm as IDisposable;
alg.SafeDispose();
alg?.Dispose();
}
_algorithm = null;
base.Dispose(disposing);
Expand Down
44 changes: 23 additions & 21 deletions Keyczar/KeyczarTest/Support/Util.cs
Original file line number Diff line number Diff line change
Expand Up @@ -217,31 +217,33 @@ protected virtual void RunTool(out object result, IList<object> stdInArgs, IList

Console.WriteLine("{0} {1}", program, combinedArg);

var process = new Process()
{
StartInfo = new ProcessStartInfo(program, combinedArg)
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
process.Start();

foreach (var stdArg in stdInArgs)
using (var process = new Process()
{
Thread.Sleep(3000);
process.StandardInput.WriteLine(stdArg.ToString());
}
StartInfo = new ProcessStartInfo(program, combinedArg)
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
})
{
process.Start();

foreach (var stdArg in stdInArgs)
{
Thread.Sleep(3000);
process.StandardInput.WriteLine(stdArg.ToString());
}

process.WaitForExit(5000);

result = process.StandardOutput.ReadToEnd();
Console.WriteLine(result);
Console.WriteLine(process.StandardError.ReadToEnd());
process.WaitForExit(5000);

result = process.StandardOutput.ReadToEnd();
Console.WriteLine(result);
Console.WriteLine(process.StandardError.ReadToEnd());
}
}
}
}
2 changes: 1 addition & 1 deletion Keyczar/KeyczarTool/Commands/AddKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ public override int Run(string[] remainingArguments)
catch (InvalidKeyTypeException ex)
#pragma warning restore 168
{
throw new ConsoleHelpAsException(String.Format(Localized.MsgMismatchedKind, type.Kind, keySet.Metadata.Kind));
throw new ConsoleHelpAsException(String.Format(Localized.MsgMismatchedKind, type?.Kind, keySet.Metadata.Kind));
}


Expand Down

0 comments on commit 8e0533d

Please sign in to comment.