using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Security; using Renci.SshNet; using Renci.SshNet.Common; using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Windows.Media.Protection.PlayReady; namespace wakka { public class SshConnection { public static string User { get; set; } = string.Empty; public static SshClient? Client { get; set; } = null; public readonly static string SshKeyPath = Path.Combine(App.LocalStroageData.Path, "key"); public static PrivateKeyFile? Key { get; set; } = null; public static string? PublicKey { get; set; } = null; public bool KeyExists() => File.Exists(SshKeyPath); public void InitializeConnection(string user) { if (!File.Exists(SshKeyPath) || user == string.Empty) { throw new InvalidOperationException("No SSH key or user is empty"); } else { User = user; Key = new PrivateKeyFile(SshKeyPath); Client = new SshClient("tilde.town", User, Key); try { Client.Connect(); } catch (SshAuthenticationException) { Key = null; throw; } } } public string RunCommand(string command) { if (Client == null || !Client.IsConnected) { throw new InvalidOperationException("SSH client is not connected."); } var rc = Client.RunCommand(command); return rc.Result; } public async void RunCommandWithInput(string command, string input) { if (Client == null || !Client.IsConnected) { throw new InvalidOperationException("SSH client is not connected."); } using (SshCommand task = Client.CreateCommand(command)) { Task executeTask = task.ExecuteAsync(CancellationToken.None); using (Stream inputStream = task.CreateInputStream()) { inputStream.Write(Encoding.UTF8.GetBytes(input)); } await executeTask; } } public string CreateSshKey() { var keygen = new SshKeyGenerator.SshKeyGenerator(2048); var privateKey = keygen.ToPrivateKey(); File.WriteAllText(SshKeyPath, privateKey); return keygen.ToRfcPublicKey("wakka"); } public void DeleteSshKey() { if (File.Exists(SshKeyPath)) { File.Delete(SshKeyPath); } } } }