public void Setup()
        {
            _rsa       = new HitaiAsymmetricEncryptionProvider();
            _rsaPublic = new HitaiAsymmetricEncryptionProvider();
            var kp = new Keypair {
                Exponent = _e,
                Modulus  = _n
            };

            kp.SetPrivateExponentAsync(_d.ToByteArray(), "password").Wait();
            _rsa.SetKeyPair(kp, "password");
            _rsaPublic.SetKeyPair(kp.ToPublic());
        }
Example #2
0
        private Keypair <string, int> TryGetKeypair(string key)
        {
            Keypair <string, int> keypair = GetKeypair(key);

            if (keypair == null)
            {
                throw new KeyNotFoundException("Avaimella " + key + " ei löytynyt timeriä.");
            }
            else
            {
                return(keypair);
            }
        }
Example #3
0
        private Keypair <string, int> TryGetKeypair(string key)
        {
            Keypair <string, int> keypair = timers.FirstOrDefault(
                k => k.Key == key);

            if (keypair == null && AutoCreateTimers)
            {
                keypair = MakeNew(key);
                timers.Add(keypair);
            }

            return(keypair);
        }
Example #4
0
        /// <summary>
        ///     Removes the keypair at <paramref name="index" /> and also removes it from the folder.
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public async Task <Keypair> RemoveKeyPair(int index)
        {
            await KeysSemaphore.WaitAsync();

            try {
                Keypair removed = Keys[index];
                await RemoveKeyPair(removed);

                return(removed);
            }
            finally {
                KeysSemaphore.Release();
            }
        }
        public PrivateKey GenerateKeyPair(String description)
        {
            CryptUtility cu      = new CryptUtility();
            Keypair      keyPair = cu.GenerateKeyPair(KEY_EMAIL);

            String publicKeyId = UploadPublicKey(keyPair.PublicKey, description);

            PrivateKey privateKey = new PrivateKey();

            privateKey.ArmoredKey  = keyPair.PrivateKey;
            privateKey.PublicKeyID = publicKeyId;

            return(privateKey);
        }
Example #6
0
        /// <summary>
        /// Palauttaa timer listasta annetulla keyllä timerin.
        /// </summary>
        public int this[string key]
        {
            get
            {
                Keypair <string, int> keypair = TryGetKeypair(key);

                return(keypair.Value);
            }
            set
            {
                Keypair <string, int> keypair = TryGetKeypair(key);

                keypair.Value = value;
            }
        }
Example #7
0
 public async Task RemoveKeyPair(Keypair key)
 {
     await LockOperation(async() => {
         if (!Keys.Remove(key))
         {
             throw new Exception("Keypair was not found");
         }
         string path = Path.Combine(Settings.KeychainFolder, $"{key.ShortId}.hit");
         if (File.Exists(path))
         {
             File.Delete(path);
         }
         OnKeypairRemoved?.Invoke(key);
         await Task.FromResult(0);
     });
 }
Example #8
0
        private Keypair Armor(AsymmetricCipherKeyPair keyPair, string email)
        {
            var privateKey = keyPair.Private;
            var publicKey  = keyPair.Public;

            var memOut    = new MemoryStream();
            var secretOut = new ArmoredOutputStream(memOut);

            var secretKey = new PgpSecretKey(
                PgpSignature.DefaultCertification,
                PublicKeyAlgorithmTag.RsaGeneral,
                publicKey,
                privateKey,
                DateTime.Now,
                email,
                SymmetricKeyAlgorithmTag.Null,
                null,
                null,
                null,
                new SecureRandom()
                );

            secretKey.Encode(secretOut);
            secretOut.Close();

            var    memPublicOut = new MemoryStream();
            Stream publicOut    = new ArmoredOutputStream(memPublicOut);

            var key = secretKey.PublicKey;

            key.Encode(publicOut);

            publicOut.Close();

            var privateKeyStr = Encoding.Default.GetString(memOut.ToArray());
            var publicKeyStr  = Encoding.Default.GetString(memPublicOut.ToArray());

            var pair = new Keypair
            {
                PrivateKey = privateKeyStr,
                PublicKey  = publicKeyStr
            };

            return(pair);
        }
Example #9
0
        /// <summary>
        /// Constructor to populate the url, token, and keypair
        /// </summary>
        public IntegrationTest()
        {
            String url;

            if (!IsNullOrEmpty(url = Environment.GetEnvironmentVariable("NCRYPTF_TEST_API")))
            {
                this.url = url;
            }

            String token;

            if (!IsNullOrEmpty(token = Environment.GetEnvironmentVariable("ACCESS_TOKEN")))
            {
                this.token = token;
            }

            this.key = Utils.GenerateKeypair();
        }
        private Keypair Armor(AsymmetricCipherKeyPair keyPair, String email)
        {
            AsymmetricKeyParameter privateKey = keyPair.Private;
            AsymmetricKeyParameter publicKey  = keyPair.Public;

            MemoryStream        memOut    = new MemoryStream();
            ArmoredOutputStream secretOut = new ArmoredOutputStream(memOut);

            PgpSecretKey secretKey = new PgpSecretKey(
                PgpSignature.DefaultCertification,
                PublicKeyAlgorithmTag.RsaGeneral,
                publicKey,
                privateKey,
                DateTime.Now,
                email,
                SymmetricKeyAlgorithmTag.Null,
                null,
                null,
                null,
                new SecureRandom()
                );

            secretKey.Encode(secretOut);
            secretOut.Close();

            MemoryStream memPublicOut = new MemoryStream();
            Stream       publicOut    = new ArmoredOutputStream(memPublicOut);

            PgpPublicKey key = secretKey.PublicKey;

            key.Encode(publicOut);

            publicOut.Close();

            String privateKeyStr = System.Text.Encoding.Default.GetString(memOut.ToArray());
            String publicKeyStr  = System.Text.Encoding.Default.GetString(memPublicOut.ToArray());

            Keypair pair = new Keypair();

            pair.PrivateKey = privateKeyStr;
            pair.PublicKey  = publicKeyStr;

            return(pair);
        }
Example #11
0
        private static async Task <Keychain> LoadAsync(string folder)
        {
            await KeysSemaphore.WaitAsync();

            try {
                var keychain = new Keychain();
                if (!Directory.Exists(folder))
                {
                    return(keychain);
                }
                foreach (string file in Directory.GetFiles(folder))
                {
                    keychain.Keys.Add(await Keypair.LoadAsync(file));
                }
                return(keychain);
            }
            finally {
                KeysSemaphore.Release();
            }
        }
Example #12
0
        /// <summary>
        ///     Adds a <paramref name="key" /> into the keychain and also saves it into the keychain folder.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task <int> AddKeyPair(Keypair key)
        {
            await KeysSemaphore.WaitAsync();

            try {
                Keys.Add(key);
                OnKeypairAdded?.Invoke(key);
                if (!Directory.Exists(Settings.KeychainFolder))
                {
                    Directory.CreateDirectory(Settings.KeychainFolder);
                }
                await key.SaveAsync(Path.Combine(Settings.KeychainFolder, $"{key.ShortId}.hit"),
                                    new HitaiArmorProvider());

                return(Keys.Count);
            }
            finally {
                KeysSemaphore.Release();
            }
        }
Example #13
0
        private async void butOk_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            byte[] bytes     = Encoding.UTF8.GetBytes(textBox.Text);
            Type   armorType = ArmorRecognizer.RecognizeArmor(bytes);
            var    armor     = Activator.CreateInstance(armorType) as IArmorProvider;

            Debug.Assert(armor != null, nameof(armor) + " != null");
            (byte[] rawData, ArmorType armorDataType) = armor.FromArmor(bytes);
            if (armorDataType != ArmorType.PublicKey)
            {
                MessageBox.Show("Vložený text není veřejný klíč.");
                Close();
                return;
            }

            await Keychain.AddKeyPair(Keypair.FromMessagePack(rawData));

            DialogResult = DialogResult.OK;
            Close();
        }
        public void AddKeypairTest()
        {
            var os = new OpenStackMember(UserName, Password, TenantName, TenantId);
            // decide keypair name which is not duplicated.
            IEnumerable <KeypairData> keypairs = os.ListKeypairs();
            IEnumerable <string>      names    = keypairs.GroupBy(s => s.KeyPair.Name, (key, g) => key);

            string[] data        = Enumerable.Range(1, 100).Select(i => string.Format("keypair-key-{0}_{1}", TesterName, i)).ToArray <string>();
            string   keypairName = (from b in data where !names.Contains <string>(b) select b).First();

            Keypair kp = os.AddKeypair(keypairName);

            Assert.IsNotNull(kp);
            Assert.IsNotNull(kp.PublicKey);
            Assert.IsNotNull(kp.FingerPrint);
            Assert.IsNotNull(kp.UserId);
            Trace.WriteLine(String.Format("keypair added : {0}", DateTime.Now));
            Trace.WriteLine(String.Format("KeypairName : {0}", kp.Name));

            // delete keypair
            Assert.IsTrue(os.DeleteKeypair(keypairName));
            Trace.WriteLine(String.Format("keypair deleted : {0}", DateTime.Now));
        }
        public void AddKeypairTest_Add_Same_Name()
        {
            var    os          = new OpenStackMember(UserName, Password, TenantName, TenantId);
            string keypairName = string.Format("keypair-key-{0}", TesterName);

            KeypairData[] keypairs = os.ListKeypairs().ToArray <KeypairData>();
            string        name     = (from b in keypairs where b.KeyPair.Name == keypairName select b.KeyPair.Name).FirstOrDefault();

            if (string.IsNullOrEmpty(name))
            {
                // add keypair
                Keypair kp = os.AddKeypair(keypairName);
                Assert.IsNotNull(kp);
                Assert.IsNotNull(kp.PublicKey);
                Assert.IsNotNull(kp.FingerPrint);
                Assert.IsNotNull(kp.UserId);
                Trace.WriteLine(String.Format("keypair added : {0}", DateTime.Now));
                Trace.WriteLine(String.Format("KeypairName : {0}", kp.Name));
            }

            // expect ServiceConflictException
            os.AddKeypair(keypairName);
        }
 public SigningKey(Keypair consumerKeypair, string signatureParameters)
     : this(consumerKeypair, null, signatureParameters)
 {
 }
 public SigningKey(Keypair consumerKeypair, Keypair clientKeypair, string signatureParameters)
 {
     ConsumerKeypair = consumerKeypair;
     ClientKeypair = clientKeypair;
     SignatureParameters = signatureParameters;
 }
Example #18
0
        public void ResetTimervalue(string key)
        {
            Keypair <string, int> keypair = TryGetKeypair(key);

            keypair.Value = 0;
        }
Example #19
0
        private void butProvest_Click(object sender, EventArgs e)
        {
            // TODO allow file import
            // todo make async
            byte[]              content       = Encoding.UTF8.GetBytes(textBox_main.Text);
            Keypair             chosenKeypair = ucKeychain_mainTab.SelectedItems.FirstOrDefault();
            IArmorProvider      armorProvider = new HitaiArmorProvider();
            Message             message;
            PasswordInputDialog passwordDialog;
            Signature           signature;
            bool correctSignature;

            switch (comboBox_actions.SelectedIndex)
            {
            case 0:     // šifrovat
                if (chosenKeypair == null)
                {
                    MessageBox.Show("Musíte vybrat klíč adresáta.");
                    return;
                }

                message = AsymmetricEncryptionController.Encrypt(chosenKeypair, content);
                byte[] armor =
                    armorProvider.ToArmor(LZ4MessagePackSerializer.Serialize(message),
                                          ArmorType.Message);
                string result = Encoding.UTF8.GetString(armor);
                Clipboard.SetText(result);
                MessageBox.Show("Výsledek byl zkopírován do schránky.");
                break;

            case 1:     // dešifrovat
                Type armorClass = ArmorRecognizer.RecognizeArmor(content);
                armorProvider = (IArmorProvider)Activator.CreateInstance(armorClass);
                (byte[] bytes, ArmorType armorType) = armorProvider.FromArmor(content);
                // TODO nechat rozpoznat akci podle ArmorType
                if (armorType != ArmorType.Message)
                {
                    MessageBox.Show("Obsah není zprávou.");
                    return;
                }

                message = LZ4MessagePackSerializer.Deserialize <Message>(bytes);
                Keypair recipient =
                    Keychain.Keys.FirstOrDefault(x => x.ShortId == message.RecipientId);
                if (recipient == null)
                {
                    MessageBox.Show("Nebyl nalezen odpovídající soukromý klíč.");
                    return;
                }

                passwordDialog = new PasswordInputDialog("Dešifrování");
                if (passwordDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                byte[] data;
                try {
                    data = AsymmetricEncryptionController.Decrypt(message,
                                                                  passwordDialog.Password,
                                                                  recipient);
                }
                catch (Exception ex) {
                    while (ex is AggregateException)
                    {
                        ex = ex.InnerException;
                    }
                    if (!(ex is CryptographicException))
                    {
                        throw;
                    }
                    MessageBox.Show("Nesprávné heslo.");
                    return;
                }

                string clearText = Encoding.UTF8.GetString(data);
                textBox_main.Text = clearText;
                break;

            case 2:     // podepsat
                if (!chosenKeypair.IsPrivate)
                {
                    MessageBox.Show("Podepisující klíč musí být soukromý.");
                    return;
                }

                passwordDialog = new PasswordInputDialog("Podepisování");
                if (passwordDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                try {
                    signature = AsymmetricEncryptionController.Sign(
                        Encoding.UTF8.GetBytes(textBox_main.Text),
                        passwordDialog.Password, chosenKeypair);
                }
                catch (Exception ex) {
                    while (ex is AggregateException)
                    {
                        ex = ex.InnerException;
                    }
                    if (!(ex is CryptographicException))
                    {
                        throw;
                    }
                    MessageBox.Show("Nesprávné heslo.");
                    return;
                }
                Clipboard.SetText(Encoding.UTF8.GetString(armorProvider.ToArmor(
                                                              LZ4MessagePackSerializer.Serialize(signature),
                                                              ArmorType.Signature)));
                MessageBox.Show("Výsledek byl zkopírován do schránky");
                break;

            case 3:     // ověřit
                armorProvider =
                    (IArmorProvider)Activator.CreateInstance(
                        ArmorRecognizer.RecognizeArmor(content));
                (byte[] bytes2, ArmorType armorType2) = armorProvider.FromArmor(content);
                if (armorType2 != ArmorType.Signature)
                {
                    MessageBox.Show("Vstup neobsahuje podpis.");
                    return;
                }

                signature        = LZ4MessagePackSerializer.Deserialize <Signature>(bytes2);
                correctSignature = AsymmetricEncryptionController.Verify(signature, Keychain);
                string clearText2;
                try {
                    clearText2 = signature.GetCleartext();
                }
                catch {
                    clearText2 = null;
                }

                MessageBox.Show((correctSignature ? "Správný podpis" : "Nesprávný podpis") +
                                (string.IsNullOrEmpty(clearText2)
                                        ? "."
                                        : " pro zprávu:\n" + clearText2));
                break;

            case 4:     // šifrovat a podepsat
                var chooseKeyDialog =
                    new ChooseKeyDialog("Vyberte klíč, kterým chcete zprávu podepsat.")
                {
                    Keychain = Keychain
                };
                if (chooseKeyDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                message        = AsymmetricEncryptionController.Encrypt(chosenKeypair, content);
                passwordDialog = new PasswordInputDialog("Podepisování");
                if (passwordDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                try {
                    signature = AsymmetricEncryptionController.Sign(message,
                                                                    passwordDialog.Password, chooseKeyDialog.ChosenKeypair);
                }
                catch (Exception ex) {
                    while (ex is AggregateException)
                    {
                        ex = ex.InnerException;
                    }
                    if (!(ex is CryptographicException))
                    {
                        throw;
                    }
                    MessageBox.Show("Nesprávné heslo.");
                    return;
                }
                result = Encoding.UTF8.GetString(armorProvider.ToArmor(
                                                     LZ4MessagePackSerializer.Serialize(signature),
                                                     ArmorType.SignedMessage));
                Clipboard.SetText(result);
                MessageBox.Show("Výsledek byl zkopírován do schránky");
                break;

            case 5:     // dešifrovat a ověřit
                armorProvider =
                    (IArmorProvider)Activator.CreateInstance(
                        ArmorRecognizer.RecognizeArmor(content));
                (byte[] bytes3, ArmorType armorType3) = armorProvider.FromArmor(content);
                if (armorType3 != ArmorType.SignedMessage)
                {
                    MessageBox.Show("Vstup neobsahuje podepsanou zprávu.");
                    return;
                }

                signature        = LZ4MessagePackSerializer.Deserialize <Signature>(bytes3);
                correctSignature = AsymmetricEncryptionController.Verify(signature, Keychain);
                if (!correctSignature)
                {
                    MessageBox.Show(
                        "Podpis není správný. Zpráva nebude dešifrována z bezpečnostních důvodů.");
                    return;
                }

                if (!signature.ContainsMessage())
                {
                    MessageBox.Show(
                        "Podpis neobsahuje zašifrovanou zprávu. Chyba.");
                    return;
                }

                passwordDialog = new PasswordInputDialog("Dešifrování");
                if (passwordDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                try {
                    result = Encoding.UTF8.GetString(
                        AsymmetricEncryptionController.Decrypt(signature.GetMessage(),
                                                               passwordDialog.Password, Keychain));
                }
                catch (Exception ex) {
                    while (ex is AggregateException)
                    {
                        ex = ex.InnerException;
                    }
                    if (!(ex is CryptographicException))
                    {
                        throw;
                    }
                    MessageBox.Show("Nesprávné heslo.");
                    return;
                }
                MessageBox.Show(
                    "Podpis byl úspěšně ověřen a dešifrovaná zpráva bude zobrazena.");
                textBox_main.Text = result;
                break;

            default:
                throw new NotImplementedException();
            }
        }