/// <summary> /// Hashes the specified data bytes. /// </summary> /// <param name="hashData">The hash data.</param> /// <returns> /// Hashed bytes /// </returns> protected override byte[] Hash(byte[] hashData) { using (var sha256 = CryptoAbstraction.CreateSHA256()) { return(sha256.ComputeHash(hashData)); } }
/// <summary> /// Hashes the specified data bytes. /// </summary> /// <param name="hashData">The hash data.</param> /// <returns> /// Hashed bytes /// </returns> protected override byte[] Hash(byte[] hashData) { using (var sha1 = CryptoAbstraction.CreateSHA1()) { return(sha1.ComputeHash(hashData, 0, hashData.Length)); } }
/// <summary> /// Initializes a new instance of the <see cref="KeyExchangeInitMessage"/> class. /// </summary> public KeyExchangeInitMessage() { var cookie = new byte[16]; CryptoAbstraction.GenerateRandom(cookie); Cookie = cookie; }
public void GetBytes() { var random = new Random(); var localChannelNumber = (uint)random.Next(0, int.MaxValue); var data = CryptoAbstraction.GenerateRandom(random.Next(10, 20)); var offset = random.Next(0, data.Length - 1); var size = random.Next(0, data.Length - offset); var target = new ChannelDataMessage(localChannelNumber, data, offset, size); var bytes = target.GetBytes(); var expectedBytesLength = 1; // Type expectedBytesLength += 4; // LocalChannelNumber expectedBytesLength += 4; // Data length expectedBytesLength += size; // Data Assert.AreEqual(expectedBytesLength, bytes.Length); var sshDataStream = new SshDataStream(bytes); Assert.AreEqual(ChannelDataMessage.MessageNumber, sshDataStream.ReadByte()); Assert.AreEqual(localChannelNumber, sshDataStream.ReadUInt32()); Assert.AreEqual((uint)size, sshDataStream.ReadUInt32()); var actualData = new byte[size]; sshDataStream.Read(actualData, 0, size); Assert.IsTrue(actualData.SequenceEqual(data.Take(offset, size))); Assert.IsTrue(sshDataStream.IsEndOfData); }
private void SetupData() { var random = new Random(); #region SftpSession.Connect() _operationTimeout = random.Next(100, 500); _protocolVersion = (uint)random.Next(0, 3); _encoding = Encoding.UTF8; _sftpInitRequestBytes = new SftpInitRequestBuilder().WithVersion(SftpSession.MaximumSupportedVersion) .Build() .GetBytes(); _sftpVersionResponse = new SftpVersionResponseBuilder().WithVersion(_protocolVersion) .Build(); _sftpRealPathRequestBytes = new SftpRealPathRequestBuilder().WithProtocolVersion(_protocolVersion) .WithRequestId(1) .WithPath(".") .WithEncoding(_encoding) .Build() .GetBytes(); _sftpNameResponse = new SftpNameResponseBuilder().WithProtocolVersion(_protocolVersion) .WithResponseId(1) .WithEncoding(_encoding) .WithFile("/ABC", SftpFileAttributes.Empty) .Build(); #endregion SftpSession.Connect() _path = random.Next().ToString(); _handle = CryptoAbstraction.GenerateRandom(4); _offset = (uint)random.Next(1, 5); _length = (uint)random.Next(30, 50); _data = CryptoAbstraction.GenerateRandom(200); _sftpOpenRequestBytes = new SftpOpenRequestBuilder().WithProtocolVersion(_protocolVersion) .WithRequestId(2) .WithFileName(_path) .WithFlags(Flags.Read) .WithEncoding(_encoding) .Build() .GetBytes(); _sftpHandleResponseBytes = new SftpHandleResponseBuilder().WithProtocolVersion(_protocolVersion) .WithResponseId(2) .WithHandle(_handle) .Build() .GetBytes(); _sftpReadRequestBytes = new SftpReadRequestBuilder().WithProtocolVersion(_protocolVersion) .WithRequestId(3) .WithHandle(_handle) .WithOffset(_offset) .WithLength(_length) .Build() .GetBytes(); _sftpDataResponseBytes = new SftpDataResponseBuilder().WithProtocolVersion(_protocolVersion) .WithResponseId(3) .WithData(_data) .Build() .GetBytes(); }
public void ShouldGenerateRandomSequenceOfValues() { var dataLength = new Random().Next(1, 100); var dataA = new byte[dataLength]; var dataB = new byte[dataLength]; CryptoAbstraction.GenerateRandom(dataA); CryptoAbstraction.GenerateRandom(dataB); Assert.IsFalse(dataA.SequenceEqual(dataB)); }
/// <summary> /// Initializes a new instance of the <see cref="DsaDigitalSignature" /> class. /// </summary> /// <param name="key">The DSA key.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <c>null</c>.</exception> public DsaDigitalSignature(DsaKey key) { if (key == null) { throw new ArgumentNullException("key"); } _key = key; _hash = CryptoAbstraction.CreateSHA1(); }
private void SetupData() { var random = new Random(); _bufferSize = (uint)random.Next(1, int.MaxValue); _openAsyncResult = new SftpOpenAsyncResult(null, null); _handle = CryptoAbstraction.GenerateRandom(random.Next(1, 10)); _statAsyncResult = new SFtpStatAsyncResult(null, null); _fileName = random.Next().ToString(); _chunkSize = (uint)random.Next(1, int.MaxValue); }
private void SetupData() { var random = new Random(); _bufferSize = (uint)random.Next(1, int.MaxValue); _openAsyncResult = new SftpOpenAsyncResult(null, null); _handle = CryptoAbstraction.GenerateRandom(random.Next(1, 10)); _statAsyncResult = new SFtpStatAsyncResult(null, null); _fileName = random.Next().ToString(); _chunkSize = (uint)random.Next(1000, 5000); _fileSize = (_chunkSize * 5) + 10; _fileAttributes = new SftpFileAttributesBuilder().WithSize(_fileSize).Build(); }
public void ShouldThrowArgumentNullExceptionWhenDataIsNull() { const byte[] data = null; try { CryptoAbstraction.GenerateRandom(data); Assert.Fail(); } catch (ArgumentNullException ex) { Assert.IsNull(ex.InnerException); Assert.AreEqual("data", ex.ParamName); } }
/// <summary> /// Initializes a new instance of the <see cref="HostKeyEventArgs"/> class. /// </summary> /// <param name="host">The host.</param> public HostKeyEventArgs(KeyHostAlgorithm host) { CanTrust = true; // Set default value HostKey = host.Data; HostKeyName = host.Name; KeyLength = host.Key.KeyLength; using (var md5 = CryptoAbstraction.CreateMd5()) { FingerPrint = md5.ComputeHash(host.Data); } }
private void SetupData() { var random = new Random(); _terminalName = random.Next().ToString(); _widthColumns = (uint)random.Next(); _heightRows = (uint)random.Next(); _widthPixels = (uint)random.Next(); _heightPixels = (uint)random.Next(); _terminalModes = new Dictionary <TerminalModes, uint>(); _bufferSize = random.Next(100, 1000); _data = CryptoAbstraction.GenerateRandom(_bufferSize); _offset = 0; _count = _data.Length; }
/// <summary> /// Applies the Bcrypt kdf to derive a key and iv from the passphrase, /// the key/iv are returned in the output variable. /// Ported from the SSHJ library. https://github.com/hierynomus/sshj /// </summary> /// <param name="password"></param> /// <param name="salt"></param> /// <param name="rounds"></param> /// <param name="output"></param> public void Pbkdf(byte[] password, byte[] salt, int rounds, byte[] output) { using (var sha512 = CryptoAbstraction.CreateSHA512()) { int nblocks = (output.Length + 31) / 32; byte[] hpass = sha512.ComputeHash(password); byte[] hsalt = new byte[64]; byte[] block_b = new byte[4]; byte[] outBytes = new byte[32]; byte[] tmp = new byte[32]; for (int block = 1; block <= nblocks; block++) { // Block count is in big endian block_b[0] = (byte)((block >> 24) & 0xFF); block_b[1] = (byte)((block >> 16) & 0xFF); block_b[2] = (byte)((block >> 8) & 0xFF); block_b[3] = (byte)(block & 0xFF); hsalt = sha512.ComputeHash(AppendArrays(salt, block_b)); Hash(hpass, hsalt, outBytes); Array.Copy(outBytes, 0, tmp, 0, outBytes.Length); for (int round = 1; round < rounds; round++) { hsalt = sha512.ComputeHash(tmp); Hash(hpass, hsalt, tmp); for (int i = 0; i < tmp.Length; i++) { outBytes[i] ^= tmp[i]; } } for (int i = 0; i < outBytes.Length; i++) { int idx = i * nblocks + (block - 1); if (idx < output.Length) { output[idx] = outBytes[i]; } } } } }
public void Load() { var random = new Random(); var localChannelNumber = (uint)random.Next(0, int.MaxValue); var data = CryptoAbstraction.GenerateRandom(random.Next(10, 20)); var offset = random.Next(0, data.Length - 1); var size = random.Next(0, data.Length - offset); var channelDataMessage = new ChannelDataMessage(localChannelNumber, data, offset, size); var bytes = channelDataMessage.GetBytes(); var target = new ChannelDataMessage(); target.Load(bytes, 1, bytes.Length - 1); // skip message type Assert.IsTrue(target.Data.SequenceEqual(data.Take(offset, size))); Assert.AreEqual(0, target.Offset); Assert.AreEqual(size, target.Size); }
private void SetupData() { var random = new Random(); _terminalName = random.Next().ToString(); _widthColumns = (uint)random.Next(); _heightRows = (uint)random.Next(); _widthPixels = (uint)random.Next(); _heightPixels = (uint)random.Next(); _terminalModes = new Dictionary <TerminalModes, uint>(); _bufferSize = random.Next(100, 1000); _bufferData = CryptoAbstraction.GenerateRandom(_bufferSize - 60); _data = CryptoAbstraction.GenerateRandom(_bufferSize - _bufferData.Length + random.Next(1, 10)); _offset = 0; _count = _data.Length; _expectedBytesSent = new ArrayBuilder <byte>().Add(_bufferData) .Add(_data, 0, _bufferSize - _bufferData.Length) .Build(); }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionInfo" /> class. /// </summary> /// <param name="host">Connection host.</param> /// <param name="port">Connection port.</param> /// <param name="username">Connection username.</param> /// <param name="proxyType">Type of the proxy.</param> /// <param name="proxyHost">The proxy host.</param> /// <param name="proxyPort">The proxy port.</param> /// <param name="proxyUsername">The proxy username.</param> /// <param name="proxyPassword">The proxy password.</param> /// <param name="authenticationMethods">The authentication methods.</param> /// <exception cref="ArgumentNullException"><paramref name="host"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException"><paramref name="username" /> is <c>null</c>, a zero-length string or contains only whitespace characters.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is not within <see cref="F:System.Net.IPEndPoint.MinPort" /> and <see cref="F:System.Net.IPEndPoint.MaxPort" />.</exception> /// <exception cref="ArgumentNullException"><paramref name="proxyType"/> is not <see cref="ProxyTypes.None"/> and <paramref name="proxyHost" /> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="proxyType"/> is not <see cref="ProxyTypes.None"/> and <paramref name="proxyPort" /> is not within <see cref="F:System.Net.IPEndPoint.MinPort" /> and <see cref="F:System.Net.IPEndPoint.MaxPort" />.</exception> /// <exception cref="ArgumentNullException"><paramref name="authenticationMethods"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException">No <paramref name="authenticationMethods"/> specified.</exception> public ConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params AuthenticationMethod[] authenticationMethods) { if (host == null) { throw new ArgumentNullException("host"); } port.ValidatePort("port"); if (username == null) { throw new ArgumentNullException("username"); } if (username.All(char.IsWhiteSpace)) { throw new ArgumentException("Cannot be empty or contain only whitespace.", "username"); } if (proxyType != ProxyTypes.None) { if (proxyHost == null) { throw new ArgumentNullException("proxyHost"); } proxyPort.ValidatePort("proxyPort"); } if (authenticationMethods == null) { throw new ArgumentNullException("authenticationMethods"); } if (authenticationMethods.Length == 0) { throw new ArgumentException("At least one authentication method should be specified.", "authenticationMethods"); } // Set default connection values Timeout = DefaultTimeout; ChannelCloseTimeout = DefaultChannelCloseTimeout; RetryAttempts = 10; MaxSessions = 10; Encoding = Encoding.UTF8; KeyExchangeAlgorithms = new Dictionary <string, Type> { { "curve25519-sha256", typeof(KeyExchangeECCurve25519) }, { "*****@*****.**", typeof(KeyExchangeECCurve25519) }, { "ecdh-sha2-nistp256", typeof(KeyExchangeECDH256) }, { "ecdh-sha2-nistp384", typeof(KeyExchangeECDH384) }, { "ecdh-sha2-nistp521", typeof(KeyExchangeECDH521) }, { "diffie-hellman-group-exchange-sha256", typeof(KeyExchangeDiffieHellmanGroupExchangeSha256) }, { "diffie-hellman-group-exchange-sha1", typeof(KeyExchangeDiffieHellmanGroupExchangeSha1) }, { "diffie-hellman-group16-sha512", typeof(KeyExchangeDiffieHellmanGroup16Sha512) }, { "diffie-hellman-group14-sha256", typeof(KeyExchangeDiffieHellmanGroup14Sha256) }, { "diffie-hellman-group14-sha1", typeof(KeyExchangeDiffieHellmanGroup14Sha1) }, { "diffie-hellman-group1-sha1", typeof(KeyExchangeDiffieHellmanGroup1Sha1) }, }; Encryptions = new Dictionary <string, CipherInfo> { { "aes256-ctr", new CipherInfo(256, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null)) }, { "3des-cbc", new CipherInfo(192, (key, iv) => new TripleDesCipher(key, new CbcCipherMode(iv), null)) }, { "aes128-cbc", new CipherInfo(128, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null)) }, { "aes192-cbc", new CipherInfo(192, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null)) }, { "aes256-cbc", new CipherInfo(256, (key, iv) => new AesCipher(key, new CbcCipherMode(iv), null)) }, { "blowfish-cbc", new CipherInfo(128, (key, iv) => new BlowfishCipher(key, new CbcCipherMode(iv), null)) }, { "twofish-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null)) }, { "twofish192-cbc", new CipherInfo(192, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null)) }, { "twofish128-cbc", new CipherInfo(128, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null)) }, { "twofish256-cbc", new CipherInfo(256, (key, iv) => new TwofishCipher(key, new CbcCipherMode(iv), null)) }, ////{"serpent256-cbc", typeof(CipherSerpent256CBC)}, ////{"serpent192-cbc", typeof(...)}, ////{"serpent128-cbc", typeof(...)}, { "arcfour", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, false)) }, { "arcfour128", new CipherInfo(128, (key, iv) => new Arc4Cipher(key, true)) }, { "arcfour256", new CipherInfo(256, (key, iv) => new Arc4Cipher(key, true)) }, ////{"idea-cbc", typeof(...)}, { "cast128-cbc", new CipherInfo(128, (key, iv) => new CastCipher(key, new CbcCipherMode(iv), null)) }, ////{"*****@*****.**", typeof(...)}, { "aes128-ctr", new CipherInfo(128, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null)) }, { "aes192-ctr", new CipherInfo(192, (key, iv) => new AesCipher(key, new CtrCipherMode(iv), null)) }, }; HmacAlgorithms = new Dictionary <string, HashInfo> { { "hmac-sha1", new HashInfo(20 * 8, CryptoAbstraction.CreateHMACSHA1) }, { "hmac-sha1-96", new HashInfo(20 * 8, key => CryptoAbstraction.CreateHMACSHA1(key, 96)) }, { "hmac-sha2-256", new HashInfo(32 * 8, CryptoAbstraction.CreateHMACSHA256) }, { "hmac-sha2-256-96", new HashInfo(32 * 8, key => CryptoAbstraction.CreateHMACSHA256(key, 96)) }, { "hmac-sha2-512", new HashInfo(64 * 8, CryptoAbstraction.CreateHMACSHA512) }, { "hmac-sha2-512-96", new HashInfo(64 * 8, key => CryptoAbstraction.CreateHMACSHA512(key, 96)) }, //{"*****@*****.**", typeof(HMacSha1)}, { "hmac-ripemd160", new HashInfo(160, CryptoAbstraction.CreateHMACRIPEMD160) }, { "*****@*****.**", new HashInfo(160, CryptoAbstraction.CreateHMACRIPEMD160) }, //{"none", typeof(...)}, }; HostKeyAlgorithms = new Dictionary <string, Func <byte[], KeyHostAlgorithm> > { { "ssh-ed25519", data => new KeyHostAlgorithm("ssh-ed25519", new ED25519Key(), data) }, #if FEATURE_ECDSA { "ecdsa-sha2-nistp256", data => new KeyHostAlgorithm("ecdsa-sha2-nistp256", new EcdsaKey(), data) }, { "ecdsa-sha2-nistp384", data => new KeyHostAlgorithm("ecdsa-sha2-nistp384", new EcdsaKey(), data) }, { "ecdsa-sha2-nistp521", data => new KeyHostAlgorithm("ecdsa-sha2-nistp521", new EcdsaKey(), data) }, #endif { "ssh-rsa", data => new KeyHostAlgorithm("ssh-rsa", new RsaKey(), data) }, { "ssh-dss", data => new KeyHostAlgorithm("ssh-dss", new DsaKey(), data) }, //{"x509v3-sign-rsa", () => { ... }, //{"x509v3-sign-dss", () => { ... }, //{"spki-sign-rsa", () => { ... }, //{"spki-sign-dss", () => { ... }, //{"pgp-sign-rsa", () => { ... }, //{"pgp-sign-dss", () => { ... }, }; CompressionAlgorithms = new Dictionary <string, Type> { //{"*****@*****.**", typeof(ZlibOpenSsh)}, //{"zlib", typeof(Zlib)}, { "none", null }, }; ChannelRequests = new Dictionary <string, RequestInfo> { { EnvironmentVariableRequestInfo.Name, new EnvironmentVariableRequestInfo() }, { ExecRequestInfo.Name, new ExecRequestInfo() }, { ExitSignalRequestInfo.Name, new ExitSignalRequestInfo() }, { ExitStatusRequestInfo.Name, new ExitStatusRequestInfo() }, { PseudoTerminalRequestInfo.Name, new PseudoTerminalRequestInfo() }, { ShellRequestInfo.Name, new ShellRequestInfo() }, { SignalRequestInfo.Name, new SignalRequestInfo() }, { SubsystemRequestInfo.Name, new SubsystemRequestInfo() }, { WindowChangeRequestInfo.Name, new WindowChangeRequestInfo() }, { X11ForwardingRequestInfo.Name, new X11ForwardingRequestInfo() }, { XonXoffRequestInfo.Name, new XonXoffRequestInfo() }, { EndOfWriteRequestInfo.Name, new EndOfWriteRequestInfo() }, { KeepAliveRequestInfo.Name, new KeepAliveRequestInfo() }, }; Host = host; Port = port; Username = username; ProxyType = proxyType; ProxyHost = proxyHost; ProxyPort = proxyPort; ProxyUsername = proxyUsername; ProxyPassword = proxyPassword; AuthenticationMethods = authenticationMethods; }
/// <summary> /// Initializes a new instance of the <see cref="RsaDigitalSignature"/> class. /// </summary> /// <param name="rsaKey">The RSA key.</param> public RsaDigitalSignature(RsaKey rsaKey) : base(new ObjectIdentifier(1, 3, 14, 3, 2, 26), new RsaCipher(rsaKey)) { _hash = CryptoAbstraction.CreateSHA1(); }
public void Test_HMac_Sha256_96_Connection() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD); connectionInfo.HmacAlgorithms.Clear(); connectionInfo.HmacAlgorithms.Add("hmac-sha2-256-96", new HashInfo(32 * 8, (key) => CryptoAbstraction.CreateHMACSHA256(key, 96))); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } }
internal byte[] GetPacket(byte paddingMultiplier, Compressor compressor) { const int outboundPacketSequenceSize = 4; var messageLength = BufferCapacity; SshDataStream sshDataStream; if (messageLength == -1 || compressor != null) { sshDataStream = new SshDataStream(DefaultCapacity); // skip: // * 4 bytes for the outbound packet sequence // * 4 bytes for the packet data length // * one byte for the packet padding length sshDataStream.Seek(outboundPacketSequenceSize + 4 + 1, SeekOrigin.Begin); if (compressor != null) { // obtain uncompressed message payload var uncompressedDataStream = new SshDataStream(messageLength != -1 ? messageLength : DefaultCapacity); WriteBytes(uncompressedDataStream); // compress message payload var compressedMessageData = compressor.Compress(uncompressedDataStream.ToArray()); // add compressed message payload sshDataStream.Write(compressedMessageData, 0, compressedMessageData.Length); } else { // add message payload WriteBytes(sshDataStream); } messageLength = (int)sshDataStream.Length - (outboundPacketSequenceSize + 4 + 1); var packetLength = messageLength + 4 + 1; // determine the padding length var paddingLength = GetPaddingLength(paddingMultiplier, packetLength); // add padding bytes var paddingBytes = new byte[paddingLength]; CryptoAbstraction.GenerateRandom(paddingBytes); sshDataStream.Write(paddingBytes, 0, paddingLength); var packetDataLength = GetPacketDataLength(messageLength, paddingLength); // skip bytes for outbound packet sequence sshDataStream.Seek(outboundPacketSequenceSize, SeekOrigin.Begin); // add packet data length sshDataStream.Write(packetDataLength.GetBytes(), 0, 4); // add packet padding length sshDataStream.WriteByte(paddingLength); } else { var packetLength = messageLength + 4 + 1; // determine the padding length var paddingLength = GetPaddingLength(paddingMultiplier, packetLength); var packetDataLength = GetPacketDataLength(messageLength, paddingLength); // lets construct an SSH data stream of the exact size required sshDataStream = new SshDataStream(packetLength + paddingLength + outboundPacketSequenceSize); // skip bytes for outbound packet sequenceSize sshDataStream.Seek(outboundPacketSequenceSize, SeekOrigin.Begin); // add packet data length sshDataStream.Write(packetDataLength.GetBytes(), 0, 4); // add packet padding length sshDataStream.WriteByte(paddingLength); // add message payload WriteBytes(sshDataStream); // add padding bytes var paddingBytes = new byte[paddingLength]; CryptoAbstraction.GenerateRandom(paddingBytes); sshDataStream.Write(paddingBytes, 0, paddingLength); } return(sshDataStream.ToArray()); }
public void ShouldPerformNoOpWhenDataIsZeroLength() { var data = new byte[0]; CryptoAbstraction.GenerateRandom(data); }