示例#1
0
        public async Task <SshKey> LoadOrCreateAsync()
        {
            var keyDir = Path.GetDirectoryName(keyPath);

            try
            {
                Directory.CreateDirectory(keyDir);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Failed to create keys directory: " + e.ToString());
                throw new SshKeyException(ErrorStrings.FailedToCreateSshKeysDirectory(e.Message));
            }

            if (!File.Exists(keyPath))
            {
                var startInfo = new ProcessStartInfo
                {
                    FileName = Path.Combine(SDKUtil.GetSshPath(),
                                            YetiConstants.SshKeygenWinExecutable),
                    Arguments = "-f \"" + keyPath + "\" -t rsa -N \"\"",
                };
                using (var process = managedProcessFactory.Create(startInfo))
                {
                    try
                    {
                        int code = await process.RunToExitAsync();

                        if (code != 0)
                        {
                            Trace.WriteLine("Key generation returned code: " + code);
                            throw new SshKeyException(ErrorStrings.SshKeyGenerationFailed(
                                                          YetiConstants.SshKeygenWinExecutable, code));
                        }
                    }
                    catch (ProcessException e)
                    {
                        Trace.WriteLine("Key generation threw: " + e.ToString());
                        throw new SshKeyException(
                                  ErrorStrings.FailedToRunSshKeyGeneration(e.Message));
                    }
                }
            }
            try
            {
                return(new SshKey {
                    PublicKey = File.ReadAllText(keyPath + ".pub")
                });
            }
            catch (Exception e)
            {
                Trace.WriteLine("Failed to read key file: " + e.ToString());
                throw new SshKeyException(ErrorStrings.FailedToReadSshKeyFile(e.Message));
            }
        }