public File(String sName, String sLocation)
 {
     Name     = sName;
     Location = sLocation;
     Size     = 0;
     Result   = EncryptionResult.NOT_PROCESSED;
 }
Exemple #2
0
        private async Task <HttpStatusCode> SendNotification(string endpoint, byte[] userKey, byte[] userSecret, byte[] data = null,
                                                             int ttl = 0, ushort padding = 0, bool randomisePadding = false)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, endpoint);

            if (endpoint.StartsWith("https://android.googleapis.com/gcm/send/"))
            {
                request.Headers.TryAddWithoutValidation("Authorization", "key=" + _firebaseServerKey);
            }
            request.Headers.Add("TTL", ttl.ToString());
            if (data != null && userKey != null && userSecret != null)
            {
                EncryptionResult package = EncryptMessage(userKey, userSecret, data, padding, randomisePadding);
                request.Content = new ByteArrayContent(package.Payload);
                request.Content.Headers.ContentType   = new MediaTypeHeaderValue("application/octet-stream");
                request.Content.Headers.ContentLength = package.Payload.Length;
                request.Content.Headers.ContentEncoding.Add("aesgcm");
                request.Headers.Add("Crypto-Key", "keyid=p256dh;dh=" + WebEncoders.Base64UrlEncode(package.PublicKey));
                request.Headers.Add("Encryption", "keyid=p256dh;salt=" + WebEncoders.Base64UrlEncode(package.Salt));
            }
            using (HttpClient hc = new HttpClient())
            {
                var response = await hc.SendAsync(request);

                return(response.StatusCode);
            }
        }
        public static bool SendNotification(string endpoint, byte[] userKey, byte[] userSecret, byte[] data = null,
                                            int ttl = 0, ushort padding = 0, bool randomisePadding = false)
        {
            HttpRequestMessage Request = new HttpRequestMessage(HttpMethod.Post, endpoint);

            if (endpoint.StartsWith("https://android.googleapis.com/gcm/send/"))
            {
                //Request.Headers.TryAddWithoutValidation("Authorization", "key=" + FirebaseServerKey);
                Request.Headers.TryAddWithoutValidation("Authorization", "key=" + ConfigurationManager.AppSettings["FCM_ServerKey"]);
            }
            Request.Headers.Add("TTL", ttl.ToString());
            if (data != null && userKey != null && userSecret != null)
            {
                EncryptionResult Package = EncryptMessage(userKey, userSecret, data, padding, randomisePadding);
                Request.Content = new ByteArrayContent(Package.Payload);
                Request.Content.Headers.ContentType   = new MediaTypeHeaderValue("application/octet-stream");
                Request.Content.Headers.ContentLength = Package.Payload.Length;
                Request.Content.Headers.ContentEncoding.Add("aesgcm");
                Request.Headers.Add("Crypto-Key", "keyid=p256dh;dh=" + WebEncoders.Base64UrlEncode(Package.PublicKey));
                Request.Headers.Add("Encryption", "keyid=p256dh;salt=" + WebEncoders.Base64UrlEncode(Package.Salt));
            }
            using (HttpClient HC = new HttpClient())
            {
                return(HC.SendAsync(Request).Result.StatusCode == HttpStatusCode.Created);
            }
        }
Exemple #4
0
        public byte[] Decrypt(EncryptionResult encrypted)
        {
            var key         = _keyring.GetOrThrow(encrypted.Kid);
            var cipherBytes = Convert.FromBase64String(encrypted.Ciphertext);
            var plainBytes  = _cipher.Decrypt(key.Bytes, cipherBytes, encrypted.Iv);

            return(plainBytes);
        }
Exemple #5
0
        /// <summary>
        /// Processes records from the input pipeline.
        /// For each input object, the command encrypts
        /// and exports the object.
        /// </summary>
        protected override void ProcessRecord()
        {
            string           exportedString   = null;
            EncryptionResult encryptionResult = null;

            const string argumentName = "SecureString";

            Utils.CheckSecureStringArg(SecureStringData, argumentName);
            if (SecureStringData.Length == 0)
            {
                throw PSTraceSource.NewArgumentException(argumentName);
            }

            if (SecureKey != null)
            {
                Dbg.Diagnostics.Assert(Key == null, "Only one encryption key should be specified");
                encryptionResult = SecureStringHelper.Encrypt(SecureString, SecureKey);
            }
            else if (Key != null)
            {
                encryptionResult = SecureStringHelper.Encrypt(SecureString, Key);
            }
            else
            {
                exportedString = SecureStringHelper.Protect(SecureString);
            }

            if (encryptionResult != null)
            {
                // The formatted string is Algorithm Version,
                // Initialization Vector, Encrypted Data
                string dataPackage = string.Format(
                    System.Globalization.CultureInfo.InvariantCulture,
                    "{0}|{1}|{2}",
                    2,
                    encryptionResult.IV,
                    encryptionResult.EncryptedData);

                // encode the package, and output it.
                // We also include a recognizable prefix so that
                // we can use the old decryption mechanism if we
                // don't see it. While the old decryption
                // generated invalid data for the first bit of the
                // SecureString, it at least didn't generate an
                // exception.
                byte[] outputBytes   = System.Text.Encoding.Unicode.GetBytes(dataPackage);
                string encodedString = Convert.ToBase64String(outputBytes);
                WriteObject(SecureStringHelper.SecureStringExportHeader + encodedString);
            }
            else if (exportedString != null)
            {
                WriteObject(exportedString);
            }
        }
 /// <summary>
 /// Decrypt the given string using the default key.
 /// </summary>
 /// <param name="strEncrypted">The string to be decrypted.</param>
 /// <returns>The container containing the decrypted string and validation results.</returns>
 public EncryptionResult Decrypt(string strEncrypted)
 {
     result = new EncryptionResult();
     try
     {
         result.DecryptedText = Decrypt(strEncrypted, _key);
         result.IsDecrypted   = true;
         return(result);
     }
     catch (Exception e)
     {
         result.Exceptions.Add(e);
         result.IsDecrypted = false;
         WriteToConsole(EncryptionManagerConstants.InvalidInput + e.Message);
         return(result);
     }
 }
        protected override void ProcessRecord()
        {
            string           str = null;
            EncryptionResult encryptionResult = null;

            Utils.CheckSecureStringArg(base.SecureStringData, "SecureString");
            if (base.SecureKey == null)
            {
                if (base.Key == null)
                {
                    str = SecureStringHelper.Protect(this.SecureString);
                }
                else
                {
                    encryptionResult = SecureStringHelper.Encrypt(this.SecureString, base.Key);
                }
            }
            else
            {
                encryptionResult = SecureStringHelper.Encrypt(this.SecureString, base.SecureKey);
            }
            if (encryptionResult == null)
            {
                if (str != null)
                {
                    base.WriteObject(str);
                }
                return;
            }
            else
            {
                object[] v = new object[3];
                v[0] = 2;
                v[1] = encryptionResult.IV;
                v[2] = encryptionResult.EncryptedData;
                string str1         = string.Format(CultureInfo.InvariantCulture, "{0}|{1}|{2}", v);
                byte[] bytes        = Encoding.Unicode.GetBytes(str1);
                string base64String = Convert.ToBase64String(bytes);
                base.WriteObject(string.Concat(SecureStringHelper.SecureStringExportHeader, base64String));
                return;
            }
        }
        public void DecryptTest()
        {
            var keyRing = new Keyring(new IKey[]
            {
                new Key("test-key", GetKey("./Docs/rsa-private.xml"))
            });
            var rsaDecrypter = new LegacyRsaDecrypter(keyRing, new LegacyRsaCipher());

            var encrypted = new EncryptionResult
            {
                Alg        = "RSA-2048-OAEP-SHA1",
                Ciphertext = cipherText,
                Kid        = "test-key"
            };

            var decryptedBytes = rsaDecrypter.Decrypt(encrypted);
            var actual         = Encoding.UTF8.GetString(decryptedBytes);

            Assert.Equal(plainText, actual);
        }
 /// <summary>
 /// Encrypt the given string using the default key.
 /// </summary>
 /// <param name="strToEncrypt">The string to be encrypted.</param>
 /// <returns>The container containing the encrypted string and validation results.</returns>
 public EncryptionResult Encrypt(string strToEncrypt)
 {
     result = new EncryptionResult();
     try
     {
         if (string.IsNullOrEmpty(_key))
         {
             _key = EncryptionConfig.DefaultEncryptionKey;
         }
         result.EncryptedText = Encrypt(strToEncrypt, _key);
         result.IsEncrypted   = true;
         return(result);
     }
     catch (Exception e)
     {
         result.Exceptions.Add(e);
         result.IsEncrypted = false;
         WriteToConsole(EncryptionManagerConstants.InvalidInput + e.Message);
         return(result);
     }
 }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            var encryptedJObject = (JObject)JToken.ReadFrom(reader);

            if (encryptedJObject.Value <string>("alg") != NonLegacyAlgorithim)
            {
                //decrypt using the legacy algorithm - will upgrade on write back
                var legacyPlainText = encryptedJObject.Decrypt(_cryptoManager, _legacySigningKeyName);
                return(ConvertToType(Encoding.UTF8.GetString(legacyPlainText)));
            }

            var encryptedResult = EncryptionResult.FromJObject(encryptedJObject);
            var plainText       = _cryptoManager.Decrypt(encryptedResult);

            return(ConvertToType(Encoding.UTF8.GetString(plainText)));
        }
Exemple #11
0
        public void Test_Encrypt_And_Decrypt()
        {
            var plainText = Encoding.UTF8.GetBytes("\"The enemy knows the system.\"");
            var encrypted = new EncryptionResult
            {
                Alg        = "AEAD_AES_256_CBC_HMAC_SHA512",
                Kid        = "test-key",
                Ciphertext =
                    "GvOMLcK5b/3YZpQJI0G8BLm98oj20ZLdqKDV3MfTuGlWL4R5p5Deykuv2XLW4LcDvnOkmhuUSRbQ8QVEmbjq43XHdOm3ColJ6LzoaAtJihk="
            };
            var provider      = new AeadAes256CbcHmacSha512Provider(new AeadAes256CbcHmacSha512Cipher(new FakeRandomNumberGenerator(Iv)), KeyRing);
            var cryptoManager = DefaultCryptoManager.Builder()
                                .Decrypter(provider.Decrypter())
                                .DefaultEncrypter(provider.Encrypter("test-key"))
                                .Build();

            var actual = cryptoManager.Encrypt(plainText);

            Assert.Equal(JsonConvert.SerializeObject(encrypted), JsonConvert.SerializeObject(actual));
            Assert.Equal(plainText, cryptoManager.Decrypt(encrypted));
        }
 public EncryptionResult Encrypt(EncryptionRequest encryptionRequest)
 {
     result = new EncryptionResult();
     try
     {
         using (FileManager fileManager = new FileManager())
         {
             FileManagerResult fileManagerResult = fileManager.GetStreamReaderText(encryptionRequest.OriginalFilePath, encryptionRequest.TextEncoding);
             if (fileManagerResult.IsFileStreamTextValid)
             {
                 if (string.IsNullOrEmpty(_key))
                 {
                     _key = EncryptionConfig.DefaultEncryptionKey;
                 }
                 result.EncryptedText       = Encrypt(fileManagerResult.FileStreamText, _key);
                 result.EncryptedToFilePath = encryptionRequest.EncryptToFilePath;
                 if (!string.IsNullOrEmpty(encryptionRequest.EncryptToFilePath))
                 {
                     SaveEncryptionToFile(encryptionRequest.EncryptToFilePath, result.EncryptedText, encryptionRequest.TextEncoding);
                     result.IsEncrypted = true;
                 }
             }
             else
             {
                 result.IsEncrypted = false;
                 result.Errors.Add(EncryptionManagerConstants.InvalidFileStream);
                 WriteToConsole(EncryptionManagerConstants.InvalidFileStream);
             }
         }
         return(result);
     }
     catch (Exception e)
     {
         result.IsEncrypted = false;
         result.Exceptions.Add(e);
         WriteToConsole(EncryptionManagerConstants.InvalidInput + e.Message);
         return(result);
     }
 }
Exemple #13
0
 public void WeEncryptAndDecryptTheString()
 {
     _result        = Manager.Encrypt(ValidKeyId, Encoding.UTF8.GetBytes(_plainText));
     _decryptResult = Manager.Decrypt(ValidKeyId, _result.EncryptedDataKey, _result.InitialisationVector, _result.EncryptedData);
 }
        /// <summary>
        /// To get a request without sending a push notification call this method.
        ///
        /// This method will throw an ArgumentException if there is an issue with the input.
        /// </summary>
        /// <param name="subscription">The PushSubscription you wish to send the notification to.</param>
        /// <param name="payload">The payload you wish to send to the user</param>
        /// <param name="options">Options for the GCM API key and vapid keys can be passed in if they are unique for each notification.</param>
        /// <returns>A HttpRequestMessage object that can be sent.</returns>
        public HttpRequestMessage GenerateRequestDetails(PushSubscription subscription, string payload, Dictionary <string, object> options = null)
        {
            if (!Uri.IsWellFormedUriString(subscription.Endpoint, UriKind.Absolute))
            {
                throw new ArgumentException(@"You must pass in a subscription with at least a valid endpoint");
            }

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, subscription.Endpoint);

            if (!String.IsNullOrEmpty(payload) && (String.IsNullOrEmpty(subscription.Auth) || String.IsNullOrEmpty(subscription.P256DH)))
            {
                throw new ArgumentException(@"To send a message with a payload, the subscription must have 'auth' and 'p256dh' keys.");
            }

            string       currentGCMAPiKey            = _gcmAPIKey;
            VapidDetails currentVapidDetails         = _vapidDetails;
            int          timeToLive                  = DefaultTtl;
            Dictionary <string, object> extraHeaders = new Dictionary <string, object>();

            if (options != null)
            {
                List <string> validOptionsKeys = new List <string> {
                    "headers", "gcmAPIKey", "vapidDetails", "TTL"
                };
                foreach (string key in options.Keys)
                {
                    if (!validOptionsKeys.Contains(key))
                    {
                        throw new ArgumentException(key + " is an invalid options. The valid options are" + String.Join(",", validOptionsKeys));
                    }
                }


                if (options.ContainsKey("headers"))
                {
                    Dictionary <string, object> headers = options["headers"] as Dictionary <string, object>;
                    if (headers == null)
                    {
                        throw new ArgumentException("options.headers must be of type Dictionary<string,object>");
                    }

                    extraHeaders = headers;
                }

                if (options.ContainsKey("gcmAPIKey"))
                {
                    string gcmAPIKey = options["gcmAPIKey"] as string;
                    if (gcmAPIKey == null)
                    {
                        throw new ArgumentException("options.gcmAPIKey must be of type string");
                    }

                    currentGCMAPiKey = gcmAPIKey;
                }

                if (options.ContainsKey("vapidDetails"))
                {
                    VapidDetails vapidDetails = options["vapidDetails"] as VapidDetails;
                    if (vapidDetails == null)
                    {
                        throw new ArgumentException("options.vapidDetails must be of type VapidDetails");
                    }

                    currentVapidDetails = vapidDetails;
                }

                if (options.ContainsKey("TTL"))
                {
                    int?ttl = options["TTL"] as int?;
                    if (ttl == null)
                    {
                        throw new ArgumentException("options.TTL must be of type int");
                    }

                    //at this stage ttl cannot be null.
                    timeToLive = (int)ttl;
                }
            }

            string cryptoKeyHeader = null;

            request.Headers.Add("TTL", timeToLive.ToString());

            foreach (KeyValuePair <string, object> header in extraHeaders)
            {
                request.Headers.Add(header.Key, header.Value.ToString());
            }

            if (!String.IsNullOrEmpty(payload))
            {
                if (String.IsNullOrEmpty(subscription.P256DH) || String.IsNullOrEmpty(subscription.Auth))
                {
                    throw new ArgumentException(@"Unable to send a message with payload to this subscription since it doesn't have the required encryption key");
                }

                EncryptionResult encryptedPayload = Encryptor.Encrypt(subscription.P256DH, subscription.Auth, payload);

                request.Content = new ByteArrayContent(encryptedPayload.Payload);
                request.Content.Headers.ContentType   = new MediaTypeHeaderValue("application/octet-stream");
                request.Content.Headers.ContentLength = encryptedPayload.Payload.Length;
                request.Content.Headers.ContentEncoding.Add("aesgcm");
                request.Headers.Add("Encryption", "salt=" + encryptedPayload.Base64EncodeSalt());
                cryptoKeyHeader = @"dh=" + encryptedPayload.Base64EncodePublicKey();
            }
            else
            {
                request.Content = new ByteArrayContent(new byte[0]);
                request.Content.Headers.ContentLength = 0;
            }

            bool isGCM = subscription.Endpoint.StartsWith(@"https://android.googleapis.com/gcm/send");

            if (isGCM)
            {
                if (!String.IsNullOrEmpty(currentGCMAPiKey))
                {
                    request.Headers.TryAddWithoutValidation("Authorization", "key=" + currentGCMAPiKey);
                }
            }
            else if (currentVapidDetails != null)
            {
                Uri    uri      = new Uri(subscription.Endpoint);
                string audience = uri.Scheme + SCHEME_DELIMITER + uri.Host;

                Dictionary <string, string> vapidHeaders = VapidHelper.GetVapidHeaders(audience, currentVapidDetails.Subject, currentVapidDetails.PublicKey, currentVapidDetails.PrivateKey);
                request.Headers.Add(@"Authorization", vapidHeaders["Authorization"]);
                if (String.IsNullOrEmpty(cryptoKeyHeader))
                {
                    cryptoKeyHeader = vapidHeaders["Crypto-Key"];
                }
                else
                {
                    cryptoKeyHeader += @";" + vapidHeaders["Crypto-Key"];
                }
            }

            request.Headers.Add("Crypto-Key", cryptoKeyHeader);
            return(request);
        }
        private async void EncryptButton_Click(object sender, RoutedEventArgs e)
        {
            bool RemoveButtonState = DisableAllControls();

            if (String.IsNullOrEmpty(TextInputEditor.Text) && fileData == null)
            {
                RestoreAllControls(RemoveButtonState);
                await new ContentDialog()
                {
                    Title = "Error", Content = "Choose file or write/paste text to encrypt!", CloseButtonText = "Okay"
                }.ShowAsync();
                EncryptButton.IsEnabled = false;
                return;
            }
            string password = "******";

            if (!PasswordSwitch.IsOn)
            {
                if (String.IsNullOrEmpty(CustomPasswordEntry.Text) || CustomPasswordEntry.Text.Length < 6 || CustomPasswordEntry.Text.Length > 16)
                {
                    RestoreAllControls(RemoveButtonState);
                    CustomPasswordEntry.Focus(FocusState.Programmatic);
                    await new ContentDialog()
                    {
                        Title = "Error", Content = "Custom Password length should be at least 6 and at most 16", CloseButtonText = "Okay"
                    }.ShowAsync();
                    return;
                }
                password = CustomPasswordEntry.Text;
            }
            if (fileData == null)
            {
                EncryptionResult encryptionResult = null;
                string           plainText        = TextInputEditor.Text;
                await Task.Run(() =>
                {
                    encryptionResult = EncryptionService.EncryptText(plainText, password);
                });

                if (encryptionResult.Result)
                {
                    var DP = new DataPackage();
                    DP.SetText(encryptionResult.EncryptedString);
                    Clipboard.SetContent(DP);
                    fileData = null;
                    RestoreAllControls(false);
                    RemoveButton_Click(null, null);
                    TextInputEditor.Text     = String.Empty;
                    CustomPasswordEntry.Text = String.Empty;
                    PasswordSwitch.IsOn      = true;
                    var FormatedTextSize = EncryptionService.GetFormatedSize(System.Text.Encoding.UTF8.GetByteCount(encryptionResult.EncryptedString));
                    await new ContentDialog()
                    {
                        Title = "Success", Content = String.Format("Text encrypted and copied to clipboard. Encrypted Text size is {0:n1}{1}", FormatedTextSize.Item1, FormatedTextSize.Item2), CloseButtonText = "Okay"
                    }.ShowAsync();
                }
                else
                {
                    await new ContentDialog()
                    {
                        Title = "Failed", Content = "Encryption failed. This text can not be encrypted. Error: \"" + encryptionResult.Error + "\"", CloseButtonText = "Okay"
                    }.ShowAsync();
                    RestoreAllControls(RemoveButtonState);
                }
            }
            else
            {
                EncryptionResult encryptionResult = null;
                await Task.Run(async() =>
                {
                    encryptionResult = await EncryptionService.EncryptFile(fileData, password);
                });

                if (encryptionResult.Result)
                {
                    ActivityText.Text = "Do not close the application. Saving encrypted file.";
                    FileSavePicker savePicker = new FileSavePicker();
                    savePicker.FileTypeChoices.Add("Crypto App Encrypted File", new List <string>()
                    {
                        ".senc"
                    });
                    savePicker.SuggestedFileName = System.IO.Path.GetFileName(encryptionResult.WritePath);
                    var writeFile = await savePicker.PickSaveFileAsync();

                    if (writeFile != null)
                    {
                        CachedFileManager.DeferUpdates(writeFile);
                        await FileIO.WriteBytesAsync(writeFile, encryptionResult.EncryptedContents);

                        FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(writeFile);

                        if (status == FileUpdateStatus.Complete)
                        {
                            await new ContentDialog()
                            {
                                Title = "Success", Content = "File is encrypted and saved as " + writeFile.Name, CloseButtonText = "Okay"
                            }.ShowAsync();
                        }
                        else
                        {
                            await new ContentDialog()
                            {
                                Title = "Failure", Content = "File could not be saved! ", CloseButtonText = "Okay"
                            }.ShowAsync();
                        }
                    }
                    else
                    {
                        await new ContentDialog()
                        {
                            Title = "Cancelled", Content = "File was not saved! ", CloseButtonText = "Okay"
                        }.ShowAsync();
                    }
                    RestoreAllControls(false);
                    fileData = null;
                    RemoveButton_Click(null, null);
                    TextInputEditor.Text     = String.Empty;
                    CustomPasswordEntry.Text = String.Empty;
                    PasswordSwitch.IsOn      = true;
                }
                else
                {
                    await new ContentDialog()
                    {
                        Title = "Failed", Content = "File encryption failed. This file can not be encrypted.Error: \"" + encryptionResult.Error + "\"", CloseButtonText = "Okay"
                    }.ShowAsync();
                    RestoreAllControls(RemoveButtonState);
                }
            }
        }
Exemple #16
0
 public static string Base64EncodePublicKey(this EncryptionResult source)
 {
     return(WebEncoder.Base64UrlEncode(source.PublicKey));
 }
Exemple #17
0
 public static string Base64EncodeSalt(this EncryptionResult source)
 {
     return(WebEncoder.Base64UrlEncode(source.Salt));
 }
        static void Main(string[] args)
        {
            Context ctx = new Context();

            if (ctx.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
            }

            Console.WriteLine("Search Bob's PGP key in the default keyring..");

            String    searchstr = "*****@*****.**";
            IKeyStore keyring   = ctx.KeyStore;

            // retrieve all keys that have Bob's email address
            Key[] keys = keyring.GetKeyList(searchstr, false);
            if (keys == null || keys.Length == 0)
            {
                Console.WriteLine("Cannot find Bob's PGP key {0} in your keyring.", searchstr);
                Console.WriteLine("You may want to create the PGP key by using the appropriate\n"
                                  + "sample in the Samples/ directory.");
                return;
            }

            // print a list of all returned keys
            foreach (Key key in keys)
            {
                if (key.Uid != null &&
                    key.Fingerprint != null)
                {
                    Console.WriteLine("Found key {0} with fingerprint {1}",
                                      key.Uid.Name,
                                      key.Fingerprint);
                }
            }

            // we are going to use the first key in the list
            PgpKey bob = (PgpKey)keys[0];

            if (bob.Uid == null || bob.Fingerprint == null)
            {
                throw new InvalidKeyException();
            }

            // Create a sample string
            StringBuilder randomtext = new StringBuilder();

            for (int i = 0; i < 80 * 6; i++)
            {
                randomtext.Append((char)(34 + i % 221));
            }
            string secrettext = new string('+', 508)
                                + " Die Gedanken sind frei "
                                + new string('+', 508)
                                + randomtext.ToString();

            Console.WriteLine("Text to be encrypted:\n\n{0}", secrettext);

            // we want our string UTF8 encoded.
            UTF8Encoding utf8 = new UTF8Encoding();

            // create a (dynamic) memory based data buffer to place the unencrypted (plain) text
            GpgmeData plain = new GpgmeMemoryData();

            // set a filename for this data buffer
            plain.FileName = "my_document.txt";

            BinaryWriter binwriter = new BinaryWriter(plain, utf8);

            // write our secret text to the memory buffer
            binwriter.Write(secrettext.ToCharArray());
            binwriter.Flush();
            // go to the beginning(!)
            binwriter.Seek(0, SeekOrigin.Begin);

            /////// ENCRYPT DATA ///////

            // we want or PGP encrypted data RADIX/BASE64 encoded.
            ctx.Armor = true;

            // create another (dynamic) memory based data buffer as destination
            GpgmeData cipher = new GpgmeMemoryData();

            cipher.FileName = "my_document.txt";

            Console.Write("Encrypt data for {0} ({1}).. ",
                          bob.Uid.Name, bob.KeyId);

            EncryptionResult encrst = ctx.Encrypt(
                new Key[] { bob },        // encrypt data to Bob's key only
                EncryptFlags.AlwaysTrust, // trust our sample PGP key
                plain,                    // source buffer
                cipher);                  // destination buffer

            Console.WriteLine("done.");
            Console.WriteLine("Cipher text:");

            // move cursor to the beginning
            cipher.Seek(0, SeekOrigin.Begin);

            /* Read cipher text from libgpgme's memory based buffer and print
             * it to the console screen.
             */
            char[] buf;
            // the cipher text is UTF8 encoded
            BinaryReader binreader = new BinaryReader(cipher, utf8);

            while (true)
            {
                try
                {
                    buf = binreader.ReadChars(255);
                    if (buf.Length == 0)
                    {
                        break;
                    }
                    Console.Write(buf);
                }
                catch (EndOfStreamException)
                {
                    break;
                }
            }

            /////// DECRYPT DATA ///////

            /* Set the password callback - needed if the user doesn't run
             * gpg-agent or any other password / pin-entry software.
             */
            ctx.SetPassphraseFunction(new PassphraseDelegate(MyPassphraseCallback));

            // go to the beginning(!)
            cipher.Seek(0, SeekOrigin.Begin);

            Console.Write("Decrypt data.. ");
            GpgmeData decryptedText = new GpgmeMemoryData();

            DecryptionResult decrst = ctx.Decrypt(
                cipher,         // source buffer
                decryptedText); // destination buffer

            Console.WriteLine("Done. Filename: \"{0}\" Recipients:",
                              decrst.FileName);

            /* print out all recipients key ids (a PGP package can be
             * encrypted to various recipients).
             */
            if (decrst.Recipients != null)
            {
                foreach (Recipient recp in decrst.Recipients)
                {
                    Console.WriteLine("\tKey id {0} with {1} algorithm",
                                      recp.KeyId,
                                      Gpgme.GetPubkeyAlgoName(recp.KeyAlgorithm));
                }
            }
            else
            {
                Console.WriteLine("\tNone");
            }

            // TEST: Compare original data and decrypted data
            byte[] orig = new byte[255], cmp = new byte[255];

            plain.Seek(0, SeekOrigin.Begin);
            decryptedText.Seek(0, SeekOrigin.Begin);

            while (true)
            {
                try
                {
                    int a, b;
                    a = plain.Read(orig, orig.Length);
                    b = decryptedText.Read(cmp, cmp.Length);

                    if (a != b)
                    {
                        throw new DecryptionFailedException("The two data buffers have different sizes.");
                    }

                    if (a == 0)
                    {
                        break; // everything okay - end of stream reached.
                    }
                    for (int i = 0; i < a; i++)
                    {
                        if (orig[i] != cmp[i])
                        {
                            throw new DecryptionFailedException("The two data buffers differ at position "
                                                                + i.ToString() + ".");
                        }
                    }
                }
                catch (EndOfStreamException)
                {
                    throw new DecryptionFailedException("The two data buffers have different sizes.");
                }
            }

            // we do not want our GpgmeData buffers destroyed
            GC.KeepAlive(binwriter);
            GC.KeepAlive(binreader);

            /////// FILE BASED DATA BUFFERS ///////

            /////// ENCRYPT FILE ///////

            // Now let's use a file based data buffers

            // create the "source" file first and fill it with our sample text.
            Console.WriteLine("Create new file plainfile.txt.");
            File.WriteAllText("plainfile.txt", secrettext, utf8);

            GpgmeData plainfile = new GpgmeFileData(
                "plainfile.txt",
                FileMode.Open,
                FileAccess.Read);

            GpgmeData cipherfile = new GpgmeFileData(
                "cipherfile.asc",
                FileMode.Create,
                FileAccess.ReadWrite);

            Console.Write("Encrypt file plainfile.txt to cipherfile.asc.. ");

            encrst = ctx.Encrypt(
                new Key[] { bob },
                EncryptFlags.AlwaysTrust,
                plainfile,
                cipherfile);

            Console.WriteLine("done.");

            plainfile.Close();
            cipherfile.Close();

            /////// DECRYPT FILE ///////

            //cipherfile = new GpgmeFileData("cipherfile.asc");
            // load the file content into the system memory
            cipherfile = new GpgmeMemoryData("cipherfile.asc");

            plainfile = new GpgmeFileData(
                "decrypted.txt",
                FileMode.Create,
                FileAccess.Write);

            Console.WriteLine("Decrypt file cipherfile.asc to decrypted.txt.. ");

            decrst = ctx.Decrypt(
                cipherfile,     // source buffer
                plainfile);     // destination buffer

            Console.WriteLine("Done. Filename: \"{0}\" Recipients:",
                              decrst.FileName);

            /* print out all recipients key ids (a PGP package can be
             * encrypted to various recipients).
             */
            if (decrst.Recipients != null)
            {
                foreach (Recipient recp in decrst.Recipients)
                {
                    Console.WriteLine("\tKey id {0} with {1} algorithm",
                                      recp.KeyId,
                                      Gpgme.GetPubkeyAlgoName(recp.KeyAlgorithm));
                }
            }
            else
            {
                Console.WriteLine("\tNone");
            }

            cipherfile.Close();
            plainfile.Close();

            return;
        }
Exemple #19
0
        private async void EncryptButton_Click(object sender, EventArgs e)
        {
            var RemoveButtonState = DisableAllControls();

            if (String.IsNullOrEmpty(TextInputEditor.Text) && fileData == null)
            {
                RestoreAllControls(RemoveButtonState);
                ShowDialog("Error", "Choose file or write/paste text to encrypt!");
                EncryptButton.Enabled = false;
                return;
            }
            if (!String.IsNullOrEmpty(TextInputEditor.Text) && fileData != null)
            {
                RestoreAllControls(RemoveButtonState);
                ShowDialog("Error", "You can encrypt either file or text at a time!");
                return;
            }
            string password = "";

            try
            {
                password = await SecureStorage.GetAsync("AppPassword");

                if (password == null)
                {
                    ShowDialog("Error", "App's password is missing. Close application and try again!");
                    return;
                }
            }
            catch (Exception)
            {
                ShowDialog("Error", "App's password is missing. Close application and try again!");
                return;
            }

            if (!PasswordSwitch.Checked)
            {
                if (String.IsNullOrEmpty(CustomPasswordEntry.Text) || CustomPasswordEntry.Text.Length < 6 || CustomPasswordEntry.Text.Length > 16)
                {
                    RestoreAllControls(RemoveButtonState);
                    ShowDialog("Error", "Custom Password length should be at least 6 and at most 16");
                    CustomPasswordEntry.RequestFocus();
                    return;
                }
                password = CustomPasswordEntry.Text;
            }
            if (fileData == null)
            {
                EncryptionResult encryptionResult = null;
                await Task.Run(() =>
                {
                    encryptionResult = EncryptionService.EncryptText(TextInputEditor.Text, password);
                });

                if (encryptionResult.Result)
                {
                    ClipboardManager clipboardManager = (ClipboardManager)this.GetSystemService(Context.ClipboardService);
                    clipboardManager.PrimaryClip = ClipData.NewPlainText("Encrypted Text", encryptionResult.EncryptedString);
                    var FormatedTextSize = EncryptionService.GetFormatedSize(System.Text.Encoding.UTF8.GetByteCount(encryptionResult.EncryptedString));
                    fileData = null;
                    RestoreAllControls(ViewStates.Invisible);
                    RemoveButton_Click(null, null);
                    TextInputEditor.Text     = String.Empty;
                    CustomPasswordEntry.Text = String.Empty;
                    PasswordSwitch.Checked   = true;
                    ShowDialog("Success", String.Format("Text encrypted and copied to clipboard. Encrypted Text size is {0:n1}{1}", FormatedTextSize.Item1, FormatedTextSize.Item2));
                }
                else
                {
                    RestoreAllControls(RemoveButtonState);
                    ShowDialog("Failed", "Encryption failed. This text can not be encrypted. Error: \"" + encryptionResult.Error + "\"");
                }
            }
            else
            {
                EncryptionResult encryptionResult = null;
                await Task.Run(() =>
                {
                    encryptionResult = EncryptionService.EncryptFile(fileData, password);
                });

                if (encryptionResult.Result)
                {
                    RestoreAllControls(ViewStates.Invisible);
                    ShowDialog("Success", "File encrypted. Encrypted filename is \"" + encryptionResult.EncryptedString + "\" and stored at \"" + "Crypto App" + "\" folder.");
                    fileData = null;
                    RemoveButton_Click(null, null);
                    TextInputEditor.Text     = String.Empty;
                    CustomPasswordEntry.Text = String.Empty;
                    PasswordSwitch.Checked   = true;
                }
                else
                {
                    RestoreAllControls(RemoveButtonState);
                    ShowDialog("Failed", "File encryption failed. This file can not be encrypted.Error: \"" + encryptionResult.Error + "\"");
                }
            }
        }
Exemple #20
0
        static void Main()
        {
            Context ctx = new Context();

            if (ctx.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
            }

            Console.WriteLine("Search Bob's and Alice's PGP keys in the default keyring..");

            String[] searchpattern = new[] {
                "*****@*****.**",
                "*****@*****.**"
            };

            IKeyStore keyring = ctx.KeyStore;

            // We want the key signatures!
            ctx.KeylistMode = KeylistMode.Signatures;

            // retrieve all keys that have Bob's or Alice's email address
            Key[] keys = keyring.GetKeyList(searchpattern, false);

            PgpKey bob = null, alice = null;

            if (keys != null && keys.Length != 0)
            {
                foreach (Key k in keys)
                {
                    if (k.Uid != null)
                    {
                        if (bob == null && k.Uid.Email.ToLower().Equals("*****@*****.**"))
                        {
                            bob = (PgpKey)k;
                        }
                        if (alice == null && k.Uid.Email.ToLower().Equals("*****@*****.**"))
                        {
                            alice = (PgpKey)k;
                        }
                    }
                    else
                    {
                        throw new InvalidKeyException();
                    }
                }
            }

            if (bob == null || alice == null)
            {
                Console.WriteLine("Cannot find Bob's or Alice's PGP key in your keyring.");
                Console.WriteLine("You may want to create the PGP keys by using the appropriate\n"
                                  + "sample in the Samples/ directory.");
                return;
            }

            // Create a sample string
            StringBuilder randomtext = new StringBuilder();

            for (int i = 0; i < 80 * 6; i++)
            {
                randomtext.Append((char)(34 + i % 221));
            }
            string origintxt         = new string('+', 508)
                                       + " Die Gedanken sind frei "
                                       + new string('+', 508)
                                       + randomtext;

            // we want our string UTF8 encoded.
            UTF8Encoding utf8 = new UTF8Encoding();

            // Write sample string to plain.txt
            File.WriteAllText("plain.txt", origintxt, utf8);

            /////// ENCRYPT AND SIGN DATA ///////

            Console.Write("Encrypt data for Bob and sign it with Alice's PGP key.. ");

            GpgmeData plain  = new GpgmeFileData("plain.txt");
            GpgmeData cipher = new GpgmeFileData("cipher.asc");

            // we want or PGP encrypted/signed data RADIX/BASE64 encoded.
            ctx.Armor = true;

            /* Set the password callback - needed if the user doesn't run
             * gpg-agent or any other password / pin-entry software.
             */
            ctx.SetPassphraseFunction(MyPassphraseCallback);

            // Set Alice's PGP key as signer
            ctx.Signers.Clear();
            ctx.Signers.Add(alice);

            EncryptionResult encrst = ctx.EncryptAndSign(
                new Key[] { bob },
                EncryptFlags.AlwaysTrust,
                plain,
                cipher);

            Console.WriteLine("done.");

            // print out invalid signature keys
            if (encrst.InvalidRecipients != null)
            {
                foreach (InvalidKey key in encrst.InvalidRecipients)
                {
                    Console.WriteLine("Invalid key: {0} ({1})",
                                      key.Fingerprint,
                                      key.Reason);
                }
            }

            plain.Close();
            cipher.Close();

            /////// DECRYPT AND VERIFY DATA ///////

            Console.Write("Decrypt and verify data.. ");

            cipher = new GpgmeFileData("cipher.asc");
            plain  = new GpgmeMemoryData();

            CombinedResult comrst = ctx.DecryptAndVerify(
                cipher, // source buffer
                plain); // destination buffer

            Console.WriteLine("Done. Filename: \"{0}\" Recipients:",
                              comrst.DecryptionResult.FileName);

            /* print out all recipients key ids (a PGP package can be
             * encrypted to various recipients).
             */
            DecryptionResult decrst = comrst.DecryptionResult;

            if (decrst.Recipients != null)
            {
                foreach (Recipient recp in decrst.Recipients)
                {
                    Console.WriteLine("\tKey id {0} with {1} algorithm",
                                      recp.KeyId,
                                      Gpgme.GetPubkeyAlgoName(recp.KeyAlgorithm));
                }
            }
            else
            {
                Console.WriteLine("\tNone");
            }

            // print out signature information
            VerificationResult verrst = comrst.VerificationResult;

            if (verrst.Signature != null)
            {
                foreach (Signature sig in verrst.Signature)
                {
                    Console.WriteLine("Verification result (signature): "
                                      + "\n\tFingerprint: {0}"
                                      + "\n\tHash algorithm: {1}"
                                      + "\n\tKey algorithm: {2}"
                                      + "\n\tTimestamp: {3}"
                                      + "\n\tSummary: {4}"
                                      + "\n\tValidity: {5}",
                                      sig.Fingerprint,
                                      Gpgme.GetHashAlgoName(sig.HashAlgorithm),
                                      Gpgme.GetPubkeyAlgoName(sig.PubkeyAlgorithm),
                                      sig.Timestamp,
                                      sig.Summary,
                                      sig.Validity);
                }
            }
        }