Skip to content

Commit ff9b1c3

Browse files
committed
Simplify sample code for verifying host identify
* Include `using` directives to make it clear that `System.Linq` and `Renci.SshNet` are required * Remove unnecessary `new byte[]` in `expectedFingerPrint` declaration * Use [discard](https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/discards) (i.e. `_`) instead unused `sender` argument (C# 7.0) * Use [Enumerable.SequenceEqual](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal) instead of manually comparing byte arrays * `using var client` without braces (C# 8.0 feature)
1 parent 592c86c commit ff9b1c3

File tree

1 file changed

+10
-26
lines changed

1 file changed

+10
-26
lines changed

README.md

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -143,33 +143,17 @@ using (var client = new SftpClient(connectionInfo))
143143
Establish a SSH connection using user name and password, and reject the connection if the fingerprint of the server does not match the expected fingerprint:
144144

145145
```cs
146-
byte[] expectedFingerPrint = new byte[] {
147-
0x66, 0x31, 0xaf, 0x00, 0x54, 0xb9, 0x87, 0x31,
148-
0xff, 0x58, 0x1c, 0x31, 0xb1, 0xa2, 0x4c, 0x6b
149-
};
146+
using System.Linq;
147+
using Renci.SshNet;
150148

151-
using (var client = new SshClient("sftp.foo.com", "guest", "pwd"))
152-
{
153-
client.HostKeyReceived += (sender, e) =>
154-
{
155-
if (expectedFingerPrint.Length == e.FingerPrint.Length)
156-
{
157-
for (var i = 0; i < expectedFingerPrint.Length; i++)
158-
{
159-
if (expectedFingerPrint[i] != e.FingerPrint[i])
160-
{
161-
e.CanTrust = false;
162-
break;
163-
}
164-
}
165-
}
166-
else
167-
{
168-
e.CanTrust = false;
169-
}
170-
};
171-
client.Connect();
172-
}
149+
byte[] expectedFingerPrint = {
150+
0x66, 0x31, 0xaf, 0x00, 0x54, 0xb9, 0x87, 0x31,
151+
0xff, 0x58, 0x1c, 0x31, 0xb1, 0xa2, 0x4c, 0x6b
152+
};
153+
154+
using var client = new SshClient("sftp.foo.com", "guest", "pwd");
155+
client.HostKeyReceived += (_, e) => e.CanTrust = expectedFingerPrint.SequenceEqual(e.FingerPrint);
156+
client.Connect();
173157
```
174158

175159
## Supporting SSH.NET

0 commit comments

Comments
 (0)