wakka/SshConnection.cs
2025-05-08 22:16:00 -05:00

77 lines
2.1 KiB
C#

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