Example #1
0
 private void MassSignDialog_Load(object sender, EventArgs e)
 {
     comboBoxSecretKey.Items.Add("");
     foreach (var secretKey in OpenPgp.Signing().ListSecretKeys())
     {
         comboBoxSecretKey.Items.Add(secretKey);
     }
 }
Example #2
0
        public void Encrypt()
        {
            // Keys generated using https://pgpkeygen.com/
            string inputFileName     = "inputFile.txt";
            string outputFileName    = "encrypted.txt";
            string publicKeyFileName = "public_key.txt";

            OpenPgp.EncryptFile(inputFileName, outputFileName, publicKeyFileName, false, false);
        }
Example #3
0
        public void Decrypt()
        {
            // Keys generated using https://pgpkeygen.com/
            string inputFileName  = "encrypted.txt";
            string outputFileName = "decrypted.txt";
            string privateKey     = "private_key.txt";
            string password       = "******";

            OpenPgp.DecryptFile(inputFileName, outputFileName, privateKey, password);
        }
        /// <summary>
        /// Loads a <see cref="Catalog"/> from an XML file and identifies the signature (if any).
        /// </summary>
        /// <param name="path">The file to load from.</param>
        /// <returns>The loaded <see cref="SignedCatalog"/>.</returns>
        /// <exception cref="IOException">A problem occurred while reading the file.</exception>
        /// <exception cref="UnauthorizedAccessException">Read access to the file is not permitted.</exception>
        /// <exception cref="InvalidDataException">A problem occurred while deserializing the XML data.</exception>
        public static SignedCatalog Load(string path)
        {
            #region Sanity checks
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            #endregion

            var openPgp = OpenPgp.Signing();
            return(new SignedCatalog(XmlStorage.LoadXml <Catalog>(path), FeedUtils.GetKey(path, openPgp), openPgp));
        }
Example #5
0
        public void DecryptSingleFileTest()
        {
            Action <byte[]> assertHelloWorld =
                bytes => Assert.AreEqual("Hello World!",
                                         new StreamReader(
                                             OpenPgp.DecryptSingleFile(new MemoryStream(bytes), TestPassphrase))
                                         .ReadToEnd());

            assertHelloWorld(_HelloWorldExampleSimpleS2K);
            assertHelloWorld(_HelloWorldSaltedS2K);
            assertHelloWorld(_HelloWorldExampleIteratedAndSaltedS2K);
        }
Example #6
0
 private void postData(string text, PictureBox picbox)
 {
     debug_no       = 13;
     picbox.Visible = true;
     try
     {
         var client = new RestClient(statusStrip1.Text.ToString());
         client.Authenticator = new HttpBasicAuthenticator(textBox1.Text.ToString(), textBox2.Text.ToString());
         debug_no             = 14;
         client.AddDefaultHeader("x-api-key", textBox3.Text.ToString());
         client.AddDefaultHeader("ContentType", "application/json");
         var request = new RestRequest(text, Method.POST, DataFormat.Json);
         debug_no = 15;
         var response = client.Post(request);
         if (((RestSharp.RestResponseBase)response).StatusDescription == "OK")
         {
             var x   = ((RestSharp.RestResponseBase)response).Content.ToString();
             obj obj = JsonConvert.DeserializeObject <obj>(x);
             debug_no = 16;
             //BUG PATH FIX
             if (textBox4.Text.Substring(textBox4.Text.Length - 1) != "\\")
             {
                 textBox4.Text = textBox4.Text + "\\";
             }
             debug_no = 17;
             File.WriteAllBytes(textBox4.Text + obj.FileName, Convert.FromBase64String(obj.Result));
             debug_no = 18;
             OpenPgp.DecryptFile(textBox4.Text + obj.FileName, textBox4.Text + text.Split('/')[text.Split('/').Length - 1].ToString() + ".ZIP", textBox5.Text, textBox6.Text);
             debug_no = 19;
             File.Delete(textBox4.Text + obj.FileName);
             debug_no = 20;
             picbox.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + "ok.png");
             picbox.BackgroundImage = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory.ToString() + "ok.png");
             debug_no = 21;
             picbox.Refresh();
             debug_no = 22;
         }
         else
         {
             MessageBox.Show(((RestSharp.RestResponseBase)response).StatusDescription);
         }
     }
     catch (Exception ex)
     {
         picbox.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + "error.png");
         picbox.BackgroundImage = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory.ToString() + "error.png");
         picbox.Refresh();
         MessageBox.Show(debug_no.ToString() + "_" + ex.Message.ToString());
     }
 }
Example #7
0
        public void EncryptSingleFileTest()
        {
            const string expectedMessage  = "Hello from C#!";
            const string expectedFileName = "HelloFromCS.txt";
            var          helloStream      = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(expectedMessage));
            var          encrypted        = OpenPgp.EncryptSingleFile(TestPassphrase, helloStream, expectedFileName);

            string decryptedFileName;
            var    decrypted = OpenPgp.DecryptSingleFile(encrypted, TestPassphrase, out decryptedFileName) as MemoryStream;

            Assert.AreEqual(expectedFileName, decryptedFileName);
            var decryptedMessage = Encoding.UTF8.GetString(decrypted.ToArray());

            Assert.AreEqual(expectedMessage, decryptedMessage);
        }
Example #8
0
        /// <summary>
        /// Saves a catalog.
        /// </summary>
        /// <param name="catalog">The catalog to save.</param>
        /// <exception cref="IOException">A file could not be read or written or the GnuPG could not be launched or the catalog file could not be written.</exception>
        /// <exception cref="UnauthorizedAccessException">Read or write access to a catalog file is not permitted.</exception>
        /// <exception cref="KeyNotFoundException">An OpenPGP key could not be found.</exception>
        private void SaveCatalog(Catalog catalog)
        {
            if (_xmlSign)
            {
                var openPgp       = OpenPgp.Signing();
                var signedCatalog = new SignedCatalog(catalog, openPgp.GetSecretKey(_key));

                PromptPassphrase(
                    () => signedCatalog.Save(_catalogFile !, _openPgpPassphrase),
                    signedCatalog.SecretKey);
            }
            else
            {
                catalog.SaveXml(_catalogFile !);
            }
        }
Example #9
0
        /// <summary>
        /// Saves a feed.
        /// </summary>
        /// <exception cref="IOException">A file could not be read or written or the GnuPG could not be launched or the feed file could not be read or written.</exception>
        /// <exception cref="UnauthorizedAccessException">Read or write access to a feed file is not permitted.</exception>
        /// <exception cref="KeyNotFoundException">An OpenPGP key could not be found.</exception>
        private void SaveFeed(FeedEditing feedEditing)
        {
            if (!feedEditing.Path !.EndsWith(".xml.template") &&
                !feedEditing.IsValid(out string problem))
            {
                Log.Warn(problem);
            }

            if (_unsign)
            {
                // Remove any existing signatures
                feedEditing.SignedFeed.SecretKey = null;
            }
            else
            {
                var openPgp = OpenPgp.Signing();
                if (_xmlSign)
                {     // Signing explicitly requested
                    if (feedEditing.SignedFeed.SecretKey == null)
                    { // No previous signature
                        // Use user-specified key or default key
                        feedEditing.SignedFeed.SecretKey = openPgp.GetSecretKey(_key);
                    }
                    else
                    {                                    // Existing signature
                        if (!string.IsNullOrEmpty(_key)) // Use new user-specified key
                        {
                            feedEditing.SignedFeed.SecretKey = openPgp.GetSecretKey(_key);
                        }
                        //else resign implied
                    }
                }
                //else resign implied
            }

            // If no signing or unsigning was explicitly requested and the content did not change
            // there is no need to overwrite (and potential resign) the file
            if (!_xmlSign && !_unsign && !feedEditing.UnsavedChanges)
            {
                return;
            }

            PromptPassphrase(
                () => feedEditing.SignedFeed.Save(feedEditing.Path !, _openPgpPassphrase),
                feedEditing.SignedFeed.SecretKey);
        }
 /// <summary>
 /// Registers a set of scoped services for using Zero Install functionality.
 /// </summary>
 /// <typeparam name="TTaskHandler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</typeparam>
 /// <param name="services">The service collection to add the services to.</param>
 public static IServiceCollection AddZeroInstall <TTaskHandler>(this IServiceCollection services)
     where TTaskHandler : class, ITaskHandler
 => services.AddScoped <ITaskHandler, TTaskHandler>()
 .AddScoped(x => Config.Load())
 .AddScoped(x => ImplementationStores.Default())
 .AddScoped(x => OpenPgp.Verifying())
 .AddScoped(x => FeedCaches.Default(x.GetService <IOpenPgp>()))
 .AddScoped(x => TrustDB.LoadSafe())
 .AddScoped <ITrustManager, TrustManager>()
 .AddScoped <IFeedManager, FeedManager>()
 .AddScoped <ICatalogManager, CatalogManager>()
 .AddScoped(x => PackageManagers.Default())
 .AddScoped <ISelectionsManager, SelectionsManager>()
 .AddScoped <ISolver, BacktrackingSolver>()
 .AddScoped <IFetcher, SequentialFetcher>()
 .AddScoped <IExecutor, Executor>()
 .AddScoped <ISelectionCandidateProvider, SelectionCandidateProvider>();
Example #11
0
 /// <summary>
 /// Registers a set of scoped services for using Zero Install functionality.
 /// </summary>
 /// <typeparam name="TTaskHandler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</typeparam>
 /// <param name="services">The service collection to add the services to.</param>
 /// <param name="configuration">An optional configuration source for building <see cref="Config"/> instead of the default config files.</param>
 public static IServiceCollection AddZeroInstall <TTaskHandler>(this IServiceCollection services, IConfiguration?configuration = null)
     where TTaskHandler : class, ITaskHandler
 => services.AddScoped <ITaskHandler, TTaskHandler>()
 .AddScoped(_ => (configuration == null) ? Config.Load() : Config.From(configuration))
 .AddScoped(_ => ImplementationStores.Default())
 .AddScoped(_ => OpenPgp.Verifying())
 .AddScoped(provider => FeedCaches.Default(provider.GetRequiredService <IOpenPgp>()))
 .AddScoped(_ => TrustDB.LoadSafe())
 .AddScoped <ITrustManager, TrustManager>()
 .AddScoped <IFeedManager, FeedManager>()
 .AddScoped <ICatalogManager, CatalogManager>()
 .AddScoped(_ => PackageManagers.Default())
 .AddScoped <ISelectionsManager, SelectionsManager>()
 .AddScoped <ISolver, BacktrackingSolver>()
 .AddScoped <IFetcher, Fetcher>()
 .AddScoped <IExecutor, Executor>()
 .AddScoped <ISelectionCandidateProvider, SelectionCandidateProvider>();
Example #12
0
        [STAThread] // Required for WinForms
        private static void Main(string[] args)
        {
            ProcessUtils.SanitizeEnvironmentVariables();
            NetUtils.ApplyProxy();

            WindowsUtils.SetCurrentProcessAppID("ZeroInstall.Publishing");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            ErrorReportForm.SetupMonitoring(new Uri("https://0install.de/error-report/"));

            var openPgp = OpenPgp.Signing();

            if (args.Length == 0)
            {
                Application.Run(new WelcomeForm(openPgp));
            }
            else
            {
                try
                {
                    var files = Paths.ResolveFiles(args, "*.xml");
                    if (files.Count == 1)
                    {
                        string path = files.First().FullName;
                        Application.Run(new MainForm(FeedEditing.Load(path), openPgp));
                    }
                    else
                    {
                        MassSignForm.Show(files);
                    }
                }
                #region Error handling
                catch (Exception ex) when(ex is ArgumentException or IOException or InvalidDataException)
                {
                    Msg.Inform(null, ex.GetMessageWithInner(), MsgSeverity.Warn);
                }
                catch (Exception ex) when(ex is UnauthorizedAccessException)
                {
                    Msg.Inform(null, ex.Message, MsgSeverity.Error);
                }
                #endregion
            }
        }
 /// <summary>
 /// Creates a new signed catalog.
 /// </summary>
 /// <param name="catalog">The wrapped <see cref="Catalog"/>.</param>
 /// <param name="secretKey">The secret key used to sign the <see cref="Catalog"/>; <c>null</c> for no signature.</param>
 /// <param name="openPgp">The OpenPGP-compatible system used to create the signatures; <c>null</c> for default.</param>
 public SignedCatalog(Catalog catalog, OpenPgpSecretKey?secretKey, IOpenPgp?openPgp = null)
 {
     Catalog   = catalog ?? throw new ArgumentNullException(nameof(catalog));
     SecretKey = secretKey;
     _openPgp  = openPgp ?? OpenPgp.Signing();
 }
Example #14
0
 /// <summary>
 /// Creates a new signed feed.
 /// </summary>
 /// <param name="feed">The wrapped <see cref="Feed"/>.</param>
 /// <param name="secretKey">The secret key used to sign the <see cref="Feed"/>; <c>null</c> for no signature.</param>
 /// <param name="openPgp">The OpenPGP-compatible system used to create the signatures; <c>null</c> for default.</param>
 public SignedFeed(Feed feed, OpenPgpSecretKey?secretKey = null, IOpenPgp?openPgp = null)
 {
     Feed      = feed ?? throw new ArgumentNullException(nameof(feed));
     SecretKey = secretKey;
     _openPgp  = openPgp ?? OpenPgp.Signing();
 }