Esempio n. 1
0
        public bool UnlockAccount(Address address, SecureString passphrase, TimeSpan?timeSpan)
        {
            if (address == Address.Zero)
            {
                return(false);
            }
            else if (IsUnlocked(address))
            {
                return(true);
            }
            else
            {
                (PrivateKey key, Result result) = _keyStore.GetKey(address, passphrase);
                if (result.ResultType == ResultType.Success)
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info($"Unlocking account: {address}");
                    }
                    _unlockedAccounts.Set(key.Address.ToString(), _protectedPrivateKeyFactory.Create(key));
                    AccountUnlocked?.Invoke(this, new AccountUnlockedEventArgs(address));
                    return(true);
                }

                if (_logger.IsError)
                {
                    _logger.Error($"Failed to unlock the account: {address}");
                }
                return(false);
            }
        }
Esempio n. 2
0
        public bool UnlockAccount(Address address, SecureString passphrase, TimeSpan?timeSpan)
        {
            if (address == Address.Zero)
            {
                return(false);
            }
            else if (IsUnlocked(address))
            {
                return(true);
            }
            else
            {
                (PrivateKey key, Result result) = _keyStore.GetKey(address, passphrase);
                if (result.ResultType == ResultType.Success)
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info($"Unlocking account: {address}");
                    }
                    _unlockedAccounts.Add(key.Address.ToString(), _protectedPrivateKeyFactory.Create(key),
                                          new CacheItemPolicy()
                    {
                        Priority = CacheItemPriority.NotRemovable, AbsoluteExpiration = _timestamper.UtcNowOffset + (timeSpan ?? DefaultExpirationTime)
                    });
                    AccountUnlocked?.Invoke(this, new AccountUnlockedEventArgs(address));
                    return(true);
                }

                if (_logger.IsError)
                {
                    _logger.Error($"Failed to unlock the account: {address}");
                }
                return(false);
            }
        }
Esempio n. 3
0
        public bool UnlockAccount(Address address, SecureString passphrase, TimeSpan?timeSpan)
        {
            if (address == Address.Zero)
            {
                return(false);
            }

            if (_unlockedAccounts.ContainsKey(address))
            {
                return(true);
            }

            (PrivateKey key, Result result) = _keyStore.GetKey(address, passphrase);
            if (result.ResultType == ResultType.Success)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"Unlocking account: {address}");
                }
                _unlockedAccounts.Add(key.Address, key);
                AccountUnlocked?.Invoke(this, new AccountUnlockedEventArgs(address));
                return(true);
            }

            if (_logger.IsError)
            {
                _logger.Error($"Failed to unlock the account: {address}");
            }
            return(false);
        }
        public bool UnlockAccount(Address address, SecureString passphrase, TimeSpan timeSpan)
        {
            if (_unlockedAccounts.ContainsKey(address))
            {
                return(true);
            }

            (PrivateKey key, Result result) = _keyStore.GetKey(address, passphrase);
            if (result.ResultType == ResultType.Success)
            {
                _unlockedAccounts.Add(key.Address, key);
                return(true);
            }

            return(false);
        }
Esempio n. 5
0
        /// <summary>
        /// Gets a Security Session.
        /// </summary>
        /// <param name="securitySessionName">The name of the Security Session.</param>
        /// <param name="keyStore">The store of all keys.</param>
        /// <returns>An object implementing ISecuritySession interface.</returns>
        public SecuritySession GetSecuritySession(string securitySessionName, IKeyStore keyStore)
        {
            lock (this.DisposeLock)
            {
                if (this.IsDisposed)
                {
                    throw OperationException.WrapException(this.DisposeReason);
                }

                lock (_securitySessions)
                {
                    SecuritySession iSecuritySession = _securitySessions[securitySessionName] as SecuritySession;
                    if (iSecuritySession == null)
                    {
                        IKeyProvider iKeyProvider = keyStore.GetKey(securitySessionName);
                        if (iKeyProvider == null)
                        {
                            throw GenuineExceptions.Get_Security_ContextNotFound(securitySessionName);
                        }
                        iSecuritySession = iKeyProvider.CreateSecuritySession(securitySessionName, this);
                        _securitySessions[securitySessionName] = iSecuritySession;
                    }

                    return(iSecuritySession);
                }
            }
        }
        public DecryptedData Decrypt(ClaimsPrincipal user, string keyName, string keyId, EncryptedData encryptedData)
        {
            user.ThrowIfNull(nameof(user));
            keyName.ThrowIfNull(nameof(keyName));
            keyId.ThrowIfNull(nameof(keyId));
            encryptedData.ThrowIfNull(nameof(encryptedData));

            var keyData = keyStore.GetKey(keyName, keyId);

            keyData.KeyAuth.CanUserAccessKey(user, keyData);

            if (encryptedData.Algorithm != "RSA-OAEP-256")
            {
                throw new ArgumentException(encryptedData.Algorithm + " is not supported");
            }

            var decryptedData = keyData.Key.Decrypt(Convert.FromBase64String(encryptedData.Value));

            return(new DecryptedData(Convert.ToBase64String(decryptedData)));
        }
Esempio n. 7
0
        public void CryptoVersionMismatchTest()
        {
            //generate key
            (PrivateKey, Result)key = _store.GenerateKey(_testPasswordSecured);
            Assert.AreEqual(ResultType.Success, key.Item2.ResultType);

            //replace version
            string       filePath = Path.Combine(_configurationProvider.GetConfig <KeystoreConfig>().KeyStoreDirectory, key.Item1.Address.ToString());
            KeyStoreItem item     = _serializer.Deserialize <KeyStoreItem>(File.ReadAllText(filePath));

            item.Crypto.Version = 0;
            string json = _serializer.Serialize(item);

            File.WriteAllText(filePath, json);

            //try to read
            (PrivateKey, Result)key2 = _store.GetKey(key.Item1.Address, _testPasswordSecured);
            Assert.AreEqual(ResultType.Failure, key2.Item2.ResultType);
            Assert.AreEqual("Crypto version mismatch", key2.Item2.Error);

            //clean up
            File.Delete(filePath);
        }
Esempio n. 8
0
 public (PrivateKey PrivateKey, Result Result) GetKey(Address address, SecureString password)
 {
     return(_keyStore.GetKey(address, password));
 }
        /// <summary>
        /// Gets a Security Session.
        /// </summary>
        /// <param name="securitySessionName">The name of the Security Session.</param>
        /// <param name="keyStore">The store of all keys.</param>
        /// <returns>An object implementing ISecuritySession interface.</returns>
        public SecuritySession GetSecuritySession(string securitySessionName, IKeyStore keyStore)
        {
            lock (this.DisposeLock)
            {
                if (this.IsDisposed)
                    throw OperationException.WrapException(this.DisposeReason);

                lock(_securitySessions)
                {
                    SecuritySession iSecuritySession = _securitySessions[securitySessionName] as SecuritySession;
                    if (iSecuritySession == null)
                    {
                        IKeyProvider iKeyProvider = keyStore.GetKey(securitySessionName);
                        if (iKeyProvider == null)
                            throw GenuineExceptions.Get_Security_ContextNotFound(securitySessionName);
                        iSecuritySession = iKeyProvider.CreateSecuritySession(securitySessionName, this);
                        _securitySessions[securitySessionName] = iSecuritySession;
                    }

                    return iSecuritySession;
                }
            }
        }
Esempio n. 10
0
        public PrivateKey LoadNodeKey()
        {
            if (_config.BlockAuthorAccount != null)
            {
                SecureString password;
                if (_config.BlockAuthorPassword != null)
                {
                    password = new SecureString();
                    foreach (var character in _config.BlockAuthorPassword)
                    {
                        password.AppendChar(character);
                    }

                    password.MakeReadOnly();
                }
                else
                {
                    password = ConsoleUtils.ReadSecret($"Provide password for validator account {_config.BlockAuthorAccount}");
                }

                try
                {
                    (PrivateKey privateKey, Result result) = _keyStore.GetKey(new Address(_config.BlockAuthorAccount), password);
                    if (result == Result.Success)
                    {
                        return(privateKey);
                    }
                    else
                    {
                        if (_logger.IsError)
                        {
                            _logger.Error($"Not able to unlock the key for {_config.BlockAuthorAccount}");
                        }
                        // continue to the other methods
                    }
                }
                catch (Exception e)
                {
                    if (_logger.IsError)
                    {
                        _logger.Error($"Not able to unlock the key for {_config.BlockAuthorAccount}", e);
                    }
                }
            }

            // this is not secure at all but this is just the node key, nothing critical so far, will use the key store here later and allow to manage by password when launching the node
            if (_config.TestNodeKey == null)
            {
                string oldPath = UnsecuredNodeKeyFilePath.GetApplicationResourcePath();
                string newPath = UnsecuredNodeKeyFilePath.GetApplicationResourcePath(_config.KeyStoreDirectory);

                if (!File.Exists(newPath))
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Generating private key for the node (no node key in configuration) - stored in plain + key store for JSON RPC unlocking");
                    }
                    using var privateKeyGenerator = new PrivateKeyGenerator(_cryptoRandom);
                    PrivateKey nodeKey           = File.Exists(oldPath) ? new PrivateKey(File.ReadAllBytes(oldPath)) : privateKeyGenerator.Generate();
                    var        keyStoreDirectory = _config.KeyStoreDirectory.GetApplicationResourcePath();
                    Directory.CreateDirectory(keyStoreDirectory);
                    File.WriteAllBytes(newPath, nodeKey.KeyBytes);
                    SecureString nodeKeyPassword = CreateNodeKeyPassword(8);
                    _keyStore.StoreKey(nodeKey, nodeKeyPassword);
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Store this password for unlocking the node key for JSON RPC - this is not secure - this log message will be in your log files. Use only in DEV contexts.");
                    }
                    if (_logger.IsInfo)
                    {
                        _logger.Info(nodeKeyPassword.Unsecure());
                    }
                }


                return(new PrivateKey(File.ReadAllBytes(newPath)));
            }

            return(new PrivateKey(_config.TestNodeKey));
        }
        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 and Alice's PGP keys in the default keyring..");

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

            IKeyStore keyring = ctx.KeyStore;

            /* Enable the listing of signatures. By default
             * key signatures are NOT passed.
             */
            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 key by using the appropriate\n"
                                  + "sample in the Samples/ directory.");
                return;
            }

            // Print out all Uids from Bob's key
            PrintUidData(bob);

            // Print out all Uids from Alice's key
            PrintUidData(alice);


            Console.WriteLine("Set Alice's PGP key as signer key.");
            // Clear signer list (remove default key)
            ctx.Signers.Clear();
            // Add Alice's key as signer
            ctx.Signers.Add(alice);

            /* 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));

            Console.WriteLine("Sign Bob's PGP key with Alice's key.. ");

            /////// SIGN KEY ///////

            PgpSignatureOptions signopts = new PgpSignatureOptions();

            signopts.SelectedUids = new int[] { 1 }; // sign the latest Uid only!
            signopts.TrustLevel   = PgpSignatureTrustLevel.Full;
            signopts.Type         = PgpSignatureType.Trust | PgpSignatureType.NonExportable;

            try
            {
                bob.Sign(ctx, signopts);
            }
            catch (AlreadySignedException)
            {
                Console.WriteLine("Bob's key is already signed!");
            }
            catch (Exception ex)
            {
                throw ex;
            }

            // Refresh Bob's key
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            PrintUidData(bob);

            /////// REVOKE SIGNATURE ///////

            Console.WriteLine("Revoke the signature..");

            // We need to find Alice's signature first
            int nsignature = 0;

            foreach (KeySignature keysig in bob.Uid.Signatures)
            {
                if (!keysig.Revoked)
                {
                    nsignature++; // do not count revocation certificates
                }
                if (keysig.KeyId.Equals(alice.KeyId) &&
                    !keysig.Revoked) // must not be a revocation certificate
                {
                    break;           // found!
                }
            }

            PgpRevokeSignatureOptions revopts = new PgpRevokeSignatureOptions();

            revopts.SelectedUid        = 1; // latest uid
            revopts.SelectedSignatures = new int[] { nsignature };
            revopts.ReasonText         = "Test revocation";

            bob.RevokeSignature(ctx, revopts);

            // Refresh Bob's key
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            PrintUidData(bob);

            /////// DELETE SIGNATURE ///////

            Console.WriteLine("Remove Alice's signature and revocation certificate(s)..");

            List <int> siglst = new List <int>();

            nsignature = 0;
            foreach (KeySignature keysig in bob.Uid.Signatures)
            {
                nsignature++;
                if (keysig.KeyId.Equals(alice.KeyId))
                {
                    siglst.Add(nsignature);
                }
            }

            PgpDeleteSignatureOptions delsigopts = new PgpDeleteSignatureOptions();

            delsigopts.DeleteSelfSignature = false;
            delsigopts.SelectedUid         = 1;
            delsigopts.SelectedSignatures  = siglst.ToArray();

            bob.DeleteSignature(ctx, delsigopts);

            // Refresh Bob's key
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            PrintUidData(bob);

            return;
        }
Esempio n. 12
0
        static void Main()
        {
            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..");

            const 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.First();

            if (bob.Uid == null || bob.Fingerprint == null)
            {
                throw new InvalidKeyException();
            }
            Console.WriteLine("\nUsing key {0}", bob.Fingerprint);

            // Change Bob's passphrase. This will usually pop-up a pin-entry window!
            ChangePassphrase(ctx, bob);

            // Add another PGP sub key to Bob's key.
            AddSubKey(ctx, bob);

            // Reload Bobs key (otherwise the new sub key is NOT visible)
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            // Display all sub keys
            DisplaySubKeys(bob);

            // Switch owner trust to "Never" an then back to "Ultimate"
            SwitchOwnerTrust(ctx, bob);

            // Disable & Enable Bob's key for usage.
            ToggleEnableDisableState(ctx, bob);

            // Set an expiration date for Bob's key (today + 5 years)
            SetExpirationDate(ctx, bob);
        }
        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();
            }

            Console.WriteLine("\nUsing key {0}", bob.Fingerprint);

            /////// CHANGE PASSPHRASE ///////

            Console.WriteLine("Change the secret key's password.");

            PgpPassphraseOptions passopts = new PgpPassphraseOptions();

            /* We need to specify our own passphrase callback methods
             * in case the user does not use gpg-agent.
             */
            passopts.OldPassphraseCallback = new PassphraseDelegate(MyPassphraseCallback);
            passopts.NewPassphraseCallback = new PassphraseDelegate(MyNewPassphraseCallback);
            passopts.EmptyOkay             = false; // we do not allow an empty passphrase

            bob.ChangePassphrase(ctx, passopts);

            /////// ADD SUBKEY ///////

            Console.Write("Add a new subkey to Bob's key.. ");

            /* 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));

            PgpSubkeyOptions subopts = new PgpSubkeyOptions();

            subopts.Algorithm = PgpSubkeyAlgorithm.RSAEncryptOnly;

            /* Same as:
             * subopts.SetAlgorithm(KeyAlgorithm.RSA);
             * subopts.Capability = AlgorithmCapability.CanEncrypt;
             */
            subopts.KeyLength      = PgpSubkeyOptions.KEY_LENGTH_4096;
            subopts.ExpirationDate = DateTime.Now.AddDays(90);

            bob.AddSubkey(ctx, subopts);

            Console.WriteLine("Done.");

            /////// VIEW SUBKEYS ///////

            // Reload Bobs key
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            Console.WriteLine("Bob has now the following sub keys:");
            int subkeycount = 0;

            foreach (Subkey subkey in bob.Subkeys)
            {
                subkeycount++;
                Console.WriteLine("{0}\n\tAlgorithm: {1}\n\t"
                                  + "Length: {2}\n\t"
                                  + "Expires: {3}\n",
                                  subkey.Fingerprint,
                                  Gpgme.GetPubkeyAlgoName(subkey.PubkeyAlgorithm),
                                  subkey.Length.ToString(),
                                  subkey.Expires.ToString());
            }
            Console.WriteLine("Found {0} sub keys.", subkeycount.ToString());

            /////// SET OWNER TRUST ///////
            Console.WriteLine("Set owner trust of Bob's key.");
            Console.Write("\tto never.. ");
            bob.SetOwnerTrust(ctx, PgpOwnerTrust.Never);
            Console.WriteLine("done.");
            Console.Write("\tto ultimate.. ");
            bob.SetOwnerTrust(ctx, PgpOwnerTrust.Ultimate);
            Console.WriteLine("done.");

            /////// ENABLE / DISABLE ///////
            Console.Write("Disable Bob's key.. ");
            bob.Disable(ctx);
            Console.WriteLine("done.");
            Console.Write("Enable Bob's key.. ");
            bob.Enable(ctx);
            Console.WriteLine("done.");

            /////// SET EXPIRE DATE ///////
            DateTime newdate = DateTime.Now.AddYears(5);

            Console.WriteLine("Set new expire date: {0}", newdate);

            PgpExpirationOptions expopts = new PgpExpirationOptions();

            expopts.ExpirationDate  = newdate;
            expopts.SelectedSubkeys = null; // only the primary key
            bob.SetExpirationDate(ctx, expopts);

            return;
        }