Inheritance: MonoBehaviour
コード例 #1
0
        public void Should_check_key_fingerprint()
        {
            var keyChain = new KeyChain(TLRig.Default, new HashServices());

            foreach (PublicKey testKey in TestData.TestPublicKeys)
            {
                keyChain.CheckKeyFingerprint(testKey).Should().BeTrue();
            }
        }
コード例 #2
0
        public void Should_compute_key_fingerprint()
        {
            var keyChain = new KeyChain(TLRig.Default, new HashServices());

            foreach (PublicKey testKey in TestData.TestPublicKeys)
            {
                ulong actual = keyChain.ComputeFingerprint(testKey.Modulus, testKey.Exponent);
                actual.Should().Be(testKey.Fingerprint);
            }
        }
コード例 #3
0
        static async Task <Stream> CreateCmsStreamAsync(
            Cid id,
            IBlockApi blockService,
            KeyChain keyChain,
            CancellationToken cancel)
        {
            var block = await blockService.GetAsync(id, cancel);

            var plain = await keyChain.ReadProtectedData(block.DataBytes, cancel);

            return(new MemoryStream(plain, false));
        }
コード例 #4
0
        /// <summary>
        /// Append a timestamp component and a random value component to interest's
        /// name. This ensures that the timestamp is greater than the timestamp used in
        /// the previous call. Then use keyChain to sign the interest which appends a
        /// SignatureInfo component and a component with the signature bits. If the
        /// interest lifetime is not set, this sets it.
        /// </summary>
        ///
        /// <param name="interest">The interest whose name is append with components.</param>
        /// <param name="keyChain">The KeyChain for calling sign.</param>
        /// <param name="certificateName">The certificate name of the key to use for signing.</param>
        /// <param name="wireFormat"></param>
        public void generate(Interest interest, KeyChain keyChain,
                             Name certificateName, WireFormat wireFormat)
        {
            prepareCommandInterestName(interest, wireFormat);
            keyChain.sign(interest, certificateName, wireFormat);

            if (interest.getInterestLifetimeMilliseconds() < 0)
            {
                // The caller has not set the interest lifetime, so set it here.
                interest.setInterestLifetimeMilliseconds(1000.0d);
            }
        }
コード例 #5
0
ファイル: Producer.cs プロジェクト: redfood/ndn-dot-net
        /// <summary>
        /// Create a Producer to use the given ProducerDb, Face and other values.
        /// A producer can produce data with a naming convention:
        /// /{prefix}/SAMPLE/{dataType}/[timestamp]
        /// The produced data packet is encrypted with a content key,
        /// which is stored in the ProducerDb database.
        /// A producer also needs to produce data containing a content key
        /// encrypted with E-KEYs. A producer can retrieve E-KEYs through the face,
        /// and will re-try for at most 3 times when E-KEY retrieval fails.
        /// </summary>
        ///
        /// <param name="prefix">The producer name prefix.</param>
        /// <param name="dataType">The dataType portion of the producer name.</param>
        /// <param name="face">The face used to retrieve keys.</param>
        /// <param name="keyChain">The keyChain used to sign data packets.</param>
        /// <param name="database">The ProducerDb database for storing keys.</param>
        public Producer(Name prefix, Name dataType, Face face, KeyChain keyChain,
                        ProducerDb database)
        {
            this.eKeyInfo_     = new Hashtable();
            this.keyRequests_  = new Hashtable();
            face_              = face;
            keyChain_          = keyChain;
            database_          = database;
            maxRepeatAttempts_ = 3;

            construct(prefix, dataType);
        }
コード例 #6
0
    // Use this for initialization
    void Start()
    {
        face_ = new Face(new TcpTransport(), new TcpTransport.ConnectionInfo(hostName));

        bootstrap_       = new Bootstrap(face_);
        keyChain_        = bootstrap_.setupDefaultIdentityAndRoot(new Name(instanceName), new Name());
        certificateName_ = bootstrap_.getDefaultCertificateName();

        // initialize the gyro instance, called when this starts, or when triggered by other components
        startGyroConsumer(gyroPrefix);
        Debug.Log(certificateName_.toUri());
    }
コード例 #7
0
        public async Task <ActionResult> Create([Bind(Include = "Id,Color,EndType,Engraved")] KeyChain keyChain)
        {
            if (ModelState.IsValid)
            {
                db.KeyChains.Add(keyChain);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(keyChain));
        }
コード例 #8
0
        static void Main(string[] args)
        {
            var data = new Data();

            data.wireDecode(new Blob(TlvData));
            Console.Out.WriteLine("Decoded Data:");
            dumpData(data);

            // Set the content again to clear the cached encoding so we encode again.
            data.setContent(data.getContent());
            var encoding = data.wireEncode();

            var reDecodedData = new Data();

            reDecodedData.wireDecode(encoding);
            Console.Out.WriteLine("");
            Console.Out.WriteLine("Re-decoded Data:");
            dumpData(reDecodedData);

            var identityStorage   = new MemoryIdentityStorage();
            var privateKeyStorage = new MemoryPrivateKeyStorage();
            var keyChain          = new KeyChain
                                        (new IdentityManager(identityStorage, privateKeyStorage),
                                        new SelfVerifyPolicyManager(identityStorage));

            // Initialize the storage.
            var keyName         = new Name("/testname/DSK-123");
            var certificateName = keyName.getSubName(0, keyName.size() - 1).append
                                      ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0");

            identityStorage.addKey(keyName, KeyType.RSA, new Blob(DEFAULT_RSA_PUBLIC_KEY_DER));
            privateKeyStorage.setKeyPairForKeyName
                (keyName, KeyType.RSA, new ByteBuffer(DEFAULT_RSA_PUBLIC_KEY_DER),
                new ByteBuffer(DEFAULT_RSA_PRIVATE_KEY_DER));

            VerifyCallbacks callbacks = new VerifyCallbacks("Re-decoded Data");

            keyChain.verifyData(reDecodedData, callbacks, callbacks);

            var freshData = new Data(new Name("/ndn/abc"));

            freshData.setContent(new Blob("SUCCESS!"));
            freshData.getMetaInfo().setFreshnessPeriod(5000);
            freshData.getMetaInfo().setFinalBlockId(new Name("/%00%09").get(0));
            keyChain.sign(freshData, certificateName);
            Console.Out.WriteLine("");
            Console.Out.WriteLine("Freshly-signed Data:");
            dumpData(freshData);

            callbacks = new VerifyCallbacks("Freshly-signed Data");
            keyChain.verifyData(freshData, callbacks, callbacks);
        }
コード例 #9
0
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            keyChain = other.GetComponent <KeyChain>();
            // Add this Key to our KeyChain
            // Play a pick-up SFX
            keyChain.AddKey(this);
            Debug.Log("You picked up the " + keyName + ". and add it to your Keychain");

            this.gameObject.SetActive(false);
        }
    }
コード例 #10
0
 /// <summary>
 /// Create a Consumer to use the given ConsumerDb, Face and other values.
 /// </summary>
 ///
 /// <param name="face">The face used for data packet and key fetching.</param>
 /// <param name="keyChain">The keyChain used to verify data packets.</param>
 /// <param name="groupName"></param>
 /// <param name="consumerName"></param>
 /// <param name="database">The ConsumerDb database for storing decryption keys.</param>
 public Consumer(Face face, KeyChain keyChain, Name groupName,
                 Name consumerName, ConsumerDb database)
 {
     this.cKeyMap_ = new Hashtable();
     this.dKeyMap_ = new Hashtable();
     database_     = database;
     keyChain_     = keyChain;
     face_         = face;
     groupName_    = new Name(groupName);
     consumerName_ = new Name(consumerName);
     cKeyLink_     = NO_LINK;
     dKeyLink_     = NO_LINK;
 }
コード例 #11
0
    private void LoadData()
    {
        string jsonString = KeyChain.GetString(_sceneDataID);

        if (string.IsNullOrEmpty(jsonString))
        {
            return;
        }

        SceneData loadedData = JsonUtility.FromJson <SceneData>(jsonString);

        SceneDataManager.ReplaceSceneData(loadedData);
    }
コード例 #12
0
ファイル: AddNewUserTest.cs プロジェクト: roymart1/BimTrackTA
        /*
         * Environnement:
         *  DEV: https://dev.bimtrack.co/en/Login
         *  QA: https://qa.bimtrack.co/en/Login
         *  PROD: https://bimtrackapp.co/en/Login (edited)
         */

        public void createUser()
        {
            KeyChain kc = CTX.keyChain;

            CTX.driver.Url = kc.UrlBimTrack;

            BTLogin login = new BTLogin();

            login.LogIn(kc.LoginUsername, kc.LoginPassword);

            BTHubsTracks btHubsTracks = new BTHubsTracks();
            ProjectList  prjList      = btHubsTracks.OpenHubByName(kc.HubName);

            prjList.SelectProject(kc.DefaultProject);

            MainProject mainProject = new MainProject();

            SideBarMenu sideBarMenu = mainProject.GetSidebarMenu();

            sideBarMenu.ClickMenuItem("Hub Settings");
            HubSettings        hubSettings = new HubSettings();
            UserManagementForm userForm    = hubSettings.ClickButtonAddUser();

            var emailSuffix = BimTrackUser.GetNewUserSuffix();
            var email       = BimTrackUser.GetUniqueUserEmail(emailSuffix);

            if (userForm.AddNewUser(new BimTrackUser(email, true)))
            {
                // PROCESS EMAIL
                BimEmailProcessor proc   = new BimEmailProcessor();
                string            szLink = null;
                while (szLink == null)
                {
                    szLink = proc.GetLatestActivationForUser(emailSuffix);
                    Console.Out.WriteLine("Loop waiting");
                    Thread.Sleep(1500);
                }

                Console.Out.WriteLine("SzLink == " + szLink);
                CTX.driver.Close();

                // Complete the user creation
                new CompleteUserFormTest().ActivateUser(szLink);

                //hubSettings.FillNewUserInformation(userSuffix, true);

                Thread.Sleep(1500);
            }

            CTX.driver.Close();
        }
コード例 #13
0
    public async Task AliceTimesoutAsync()
    {
        // Alice times out when its deadline is reached.
        WabiSabiConfig cfg       = new();
        var            round     = WabiSabiFactory.CreateRound(cfg);
        var            km        = ServiceFactory.CreateKeyManager("");
        var            key       = BitcoinFactory.CreateHdPubKey(km);
        var            smartCoin = BitcoinFactory.CreateSmartCoin(key, 10m);
        var            rpc       = WabiSabiFactory.CreatePreconfiguredRpcClient(smartCoin.Coin);

        using Arena arena = await ArenaBuilder.From(cfg).With(rpc).CreateAndStartAsync(round);

        var arenaClient = WabiSabiFactory.CreateArenaClient(arena);

        using RoundStateUpdater roundStateUpdater = new(TimeSpan.FromSeconds(2), arena);
        await roundStateUpdater.StartAsync(CancellationToken.None);

        // Register Alices.
        var keyChain = new KeyChain(km, new Kitchen(""));

        using CancellationTokenSource cancellationTokenSource = new();
        var task = AliceClient.CreateRegisterAndConfirmInputAsync(RoundState.FromRound(round), arenaClient, smartCoin, keyChain, roundStateUpdater, cancellationTokenSource.Token);

        while (round.Alices.Count == 0)
        {
            await Task.Delay(10);
        }

        var alice = Assert.Single(round.Alices);

        alice.Deadline = DateTimeOffset.UtcNow - TimeSpan.FromMilliseconds(1);
        await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21));

        Assert.Empty(round.Alices);

        cancellationTokenSource.Cancel();

        try
        {
            await task;
            throw new InvalidOperationException("The operation should throw!");
        }
        catch (Exception exc)
        {
            Assert.True(exc is OperationCanceledException or WabiSabiProtocolException);
        }

        await roundStateUpdater.StopAsync(CancellationToken.None);

        await arena.StopAsync(CancellationToken.None);
    }
コード例 #14
0
        // Deletes keychains

        public async Task <ActionResult> Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            KeyChain keyChain = await db.KeyChains.FindAsync(id);

            if (keyChain == null)
            {
                return(HttpNotFound());
            }
            return(View(keyChain));
        }
コード例 #15
0
        public void Should_add_keys()
        {
            var keyChain = new KeyChain(TLRig.Default, new HashServices());

            keyChain.AddKeys(TestData.TestPublicKeys);

            foreach (PublicKey testKey in TestData.TestPublicKeys)
            {
                keyChain.Contains(testKey.Fingerprint).Should().BeTrue("Because key chain must have added key with fingerprint: {0:X16}.", testKey.Fingerprint);
                PublicKey key = keyChain[testKey.Fingerprint];
                key.Should().NotBeNull();
                key.ShouldBeEquivalentTo(testKey);
            }
        }
コード例 #16
0
ファイル: DoorControl.cs プロジェクト: BanksR/KeysAndDoors
    // Upon a trigger, if zombie let it pass.
    // If Player do the OpenDoor Function.
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Zombie"))
        {
            _anims.SetTrigger("Open");
            _doorCollider.enabled = false;
        }

        if (other.gameObject.CompareTag("Player"))
        {
            KeyChain keysInInventory = other.GetComponent <KeyChain>();
            OpenDoor(keysInInventory);
        }
    }
コード例 #17
0
        public void Should_add_keys()
        {
            var keyChain = new KeyChain(TLRig.Default, new HashServices());

            keyChain.AddKeys(TestData.TestPublicKeys);

            foreach (PublicKey testKey in TestData.TestPublicKeys)
            {
                keyChain.Contains(testKey.Fingerprint).Should().BeTrue("Because key chain must have added key with fingerprint: {0:X16}.", testKey.Fingerprint);
                PublicKey key = keyChain[testKey.Fingerprint];
                key.Should().NotBeNull();
                key.ShouldBeEquivalentTo(testKey);
            }
        }
コード例 #18
0
ファイル: Producer.cs プロジェクト: vcgato29/ndn-dot-net
        /// <summary>
        /// Create a Producer to use the given ProducerDb, Face and other values.
        /// A producer can produce data with a naming convention:
        /// /{prefix}/SAMPLE/{dataType}/[timestamp]
        /// The produced data packet is encrypted with a content key,
        /// which is stored in the ProducerDb database.
        /// A producer also needs to produce data containing a content key
        /// encrypted with E-KEYs. A producer can retrieve E-KEYs through the face,
        /// and will re-try for at most repeatAttemps times when E-KEY retrieval fails.
        /// </summary>
        ///
        /// <param name="prefix">The producer name prefix. This makes a copy of the Name.</param>
        /// <param name="dataType"></param>
        /// <param name="face">The face used to retrieve keys.</param>
        /// <param name="keyChain">The keyChain used to sign data packets.</param>
        /// <param name="database">The ProducerDb database for storing keys.</param>
        /// <param name="repeatAttempts">The maximum retry for retrieving keys.</param>
        /// <param name="keyRetrievalLink">getDelegations().size() is zero, don't use it.</param>
        public Producer(Name prefix, Name dataType, Face face, KeyChain keyChain,
                        ProducerDb database, int repeatAttempts, Link keyRetrievalLink)
        {
            this.eKeyInfo_     = new Hashtable();
            this.keyRequests_  = new Hashtable();
            face_              = face;
            keyChain_          = keyChain;
            database_          = database;
            maxRepeatAttempts_ = repeatAttempts;
            // Copy the Link object.
            keyRetrievalLink_ = new Link(keyRetrievalLink);

            construct(prefix, dataType);
        }
コード例 #19
0
 /// <summary>
 /// Create a Consumer to use the given ConsumerDb, Face and other values.
 /// </summary>
 ///
 /// <param name="face">The face used for data packet and key fetching.</param>
 /// <param name="keyChain">The keyChain used to verify data packets.</param>
 /// <param name="groupName"></param>
 /// <param name="consumerName"></param>
 /// <param name="database">The ConsumerDb database for storing decryption keys.</param>
 /// <param name="cKeyLink">getDelegations().size() is zero, don't use it.</param>
 /// <param name="dKeyLink">getDelegations().size() is zero, don't use it.</param>
 public Consumer(Face face, KeyChain keyChain, Name groupName,
                 Name consumerName, ConsumerDb database, Link cKeyLink, Link dKeyLink)
 {
     this.cKeyMap_ = new Hashtable();
     this.dKeyMap_ = new Hashtable();
     database_     = database;
     keyChain_     = keyChain;
     face_         = face;
     groupName_    = new Name(groupName);
     consumerName_ = new Name(consumerName);
     // Copy the Link object.
     cKeyLink_ = new Link(cKeyLink);
     dKeyLink_ = new Link(dKeyLink);
 }
コード例 #20
0
        private static int EncryptKeyChain(string[] args)
        {
            CommandLine cmdLine  = new CommandLine(args, false);
            string      inPath   = cmdLine.GetOption("in", null);
            string      outPath  = cmdLine.GetOption("out", null);
            string      key      = cmdLine.GetOption("key", null);
            KeyChain    keyChain = new KeyChain();

            if (inPath == null)
            {
                Program.Error("[-in:<path>] command line option is required.");
                return(1);
            }

            if (outPath == null)
            {
                Program.Error("[-out:<path>] command line option is required.");
                return(1);
            }

            if (key == null)
            {
                Program.Error("[-key:<symkey>] command line option is required.");
                return(1);
            }

            using (var input = new StreamReader(inPath))
            {
                for (var line = input.ReadLine(); line != null; line = input.ReadLine())
                {
                    var trimmed = line.Trim();

                    if (trimmed.Length == 0 || trimmed.StartsWith("//") || trimmed.StartsWith("--"))
                    {
                        continue;
                    }

                    keyChain.Add(trimmed);
                }
            }

            using (var output = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
            {
                var encrypted = keyChain.Encrypt(new SymmetricKey(key));

                output.Write(encrypted, 0, encrypted.Length);
            }

            return(0);
        }
コード例 #21
0
    public void start()
    {
        // generic face setup
        face_ = new Face(new TcpTransport(), new TcpTransport.ConnectionInfo(hostName_));

        bootstrap_       = new Bootstrap(face_);
        keyChain_        = bootstrap_.setupDefaultIdentityAndRoot(new Name(instanceName_), new Name());
        certificateName_ = bootstrap_.getDefaultCertificateName();

        // class-specific start
        memoryContentCache_ = new MemoryContentCache(face_);

        fetchPrefix_ = new Name(instanceName_).append(fetchVerb);
        linkPrefix_  = new Name(instanceName_).append(linkVerb);

        FetchInterestHandler fh = new FetchInterestHandler(this);

        memoryContentCache_.registerPrefix(fetchPrefix_, fh, fh);

        LinkInterestHandler lh = new LinkInterestHandler(this);

        face_.registerPrefix(linkPrefix_, lh, lh);

        // publish html content for given mobile, call when needed
        // for this example call this on start
        string htmlString = "<p>Hello world!</p>";
        string mobileName = "/home/browser1";

        publishHtmlForMobile(mobileName, htmlString);

        // update event
        while (true)
        {
            face_.processEvents();
            System.Threading.Thread.Sleep(5);

            // dummy for testing repeated fetch on consumer
            if (nextThreshold_ > 0)
            {
                cycleCount_ += 1;
                if (cycleCount_ > nextThreshold_)
                {
                    htmlString = "<p>" + PhoneHandler.randomString(5) + "</p>";
                    publishHtmlForMobile(mobileName, htmlString);
                    cycleCount_ = 0;
                }
            }
        }
    }
コード例 #22
0
        /// <summary>
        /// Create an AccessManagerV2 to serve the NAC public key for other data
        /// producers to fetch, and to serve encrypted versions of the private keys
        /// (as safe bags) for authorized consumers to fetch.
        /// KEK and KDK naming:
        /// [identity]/NAC/[dataset]/KEK            /[key-id]                           (== KEK, public key)
        /// [identity]/NAC/[dataset]/KDK/[key-id]   /ENCRYPTED-BY/[user]/KEY/[key-id]   (== KDK, encrypted private key)
        /// \_____________  ______________/
        /// \/
        /// registered with NFD
        /// </summary>
        ///
        /// <param name="identity"></param>
        /// <param name="dataset">The name of dataset that this manager is controlling.</param>
        /// <param name="keyChain">The KeyChain used to sign Data packets.</param>
        /// <param name="face"></param>
        public AccessManagerV2(PibIdentity identity, Name dataset,
                               KeyChain keyChain, Face face)
        {
            this.storage_ = new InMemoryStorageRetaining();
            identity_     = identity;
            keyChain_     = keyChain;
            face_         = face;

            // The NAC identity is: <identity>/NAC/<dataset>
            // Generate the NAC key.
            PibIdentity nacIdentity = keyChain_.createIdentityV2(
                new Name(identity.getName()).append(
                    net.named_data.jndn.encrypt.EncryptorV2.NAME_COMPONENT_NAC).append(dataset),
                new RsaKeyParams());

            nacKey_ = nacIdentity.getDefaultKey();
            if (nacKey_.getKeyType() != net.named_data.jndn.security.KeyType.RSA)
            {
                logger_.log(ILOG.J2CsMapping.Util.Logging.Level.INFO,
                            "Cannot re-use existing KEK/KDK pair, as it is not an RSA key, regenerating");
                nacKey_ = keyChain_.createKey(nacIdentity, new RsaKeyParams());
            }
            Name.Component nacKeyId = nacKey_.getName().get(-1);

            Name kekPrefix = new Name(nacKey_.getIdentityName())
                             .append(net.named_data.jndn.encrypt.EncryptorV2.NAME_COMPONENT_KEK);

            Data kekData = new Data(nacKey_.getDefaultCertificate());

            kekData.setName(new Name(kekPrefix).append(nacKeyId));
            kekData.getMetaInfo().setFreshnessPeriod(
                DEFAULT_KEK_FRESHNESS_PERIOD_MS);
            keyChain_.sign(kekData, new SigningInfo(identity_));
            // A KEK looks like a certificate, but doesn't have a ValidityPeriod.
            storage_.insert(kekData);

            OnInterestCallback serveFromStorage = new AccessManagerV2.Anonymous_C1(this);

            OnRegisterFailed onRegisterFailed = new AccessManagerV2.Anonymous_C0();

            kekRegisteredPrefixId_ = face_.registerPrefix(kekPrefix,
                                                          serveFromStorage, onRegisterFailed);

            Name kdkPrefix = new Name(nacKey_.getIdentityName()).append(
                net.named_data.jndn.encrypt.EncryptorV2.NAME_COMPONENT_KDK).append(nacKeyId);

            kdkRegisteredPrefixId_ = face_.registerPrefix(kdkPrefix,
                                                          serveFromStorage, onRegisterFailed);
        }
コード例 #23
0
ファイル: DoorControl.cs プロジェクト: BanksR/KeysAndDoors
    // This function will loop through every key in the players
    // KeyChain List of Keys. If it finds a key that matches the DoorID,
    // it will open the door.
    public void OpenDoor(KeyChain keysToCheck)
    {
        foreach (var key in keysToCheck.keys)
        {
            if (key.keyID == DoorID)
            {
                _anims.SetTrigger("Open");
                keysToCheck.RemoveKey(key);
                _doorCollider.enabled = false;
                return;
            }
        }

        Debug.Log("Door Remains Locked - find the correct Key!");
    }
コード例 #24
0
 /// <summary>
 /// Create a DecryptorV2 with the given parameters.
 /// </summary>
 ///
 /// <param name="credentialsKey"></param>
 /// <param name="validator"></param>
 /// <param name="keyChain">The KeyChain that will be used to decrypt the KDK.</param>
 /// <param name="face">The Face that will be used to fetch the CK and KDK.</param>
 public DecryptorV2(PibKey credentialsKey, Validator validator,
                    KeyChain keyChain, Face face)
 {
     this.contentKeys_ = new Hashtable <Name, ContentKey>();
     credentialsKey_   = credentialsKey;
     // validator_ = validator;
     face_     = face;
     keyChain_ = keyChain;
     try {
         internalKeyChain_ = new KeyChain("pib-memory:", "tpm-memory:");
     } catch (Exception ex) {
         // We are just creating an in-memory store, so we don't expect an error.
         throw new Exception("Error creating in-memory KeyChain: " + ex);
     }
 }
コード例 #25
0
ファイル: MDIChildForm.cs プロジェクト: jaredmael/Keypass
 public void LoadFile()
 {
     if (KeyChainManager.KeyChain.Name != String.Empty)
     {
         this.Text = Path.GetFileName(KeyChainManager.KeyChain.Name);
     }
     //this to show info loaded when load is run from main need to add groups to Grouptree and keys to keylist
     foreach (Group g in KeyChainManager.KeyChain.Groups)
     {
         groupTreeControl1.AddTreeNodefromFileLoad(g);
         gSelected = g;
         kSelected = ContextManager.SingularKey;
     }
     this.kc = KeyChainManager.KeyChain;
 }
コード例 #26
0
        public async Task <bool> LoginAsync()
        {
            EnsureAuthClient();
            LoginResult result = null;

            try
            {
                result = await _client.LoginAsync(new LoginRequest());
            }
            catch (Exception e)
            {
                Debug.Log("UnityAuthClient::Exception during login: "******"UnityAuthClient::Dismissing sign-in browser.");
                Browser.Dismiss();
            }

            if (result.IsError)
            {
                Debug.Log("UnityAuthClient::Error authenticating: " + result.Error);
            }
            else
            {
                AccessToken   = result.AccessToken;
                RefreshToken  = result.RefreshToken;
                IdentityToken = result.IdentityToken;
                if (result.User.Identity.Name != null)
                {
                    UserName = result.User.Identity.Name;
                }
                AccessTokenExpiration = result.AccessTokenExpiration;

                KeyChain.SetString(refreshKey, RefreshToken);
                KeyChain.SetString(nameKey, UserName);

                Debug.Log("UnityAuthClient::AccessToken: " + AccessToken);
                Debug.Log("UnityAuthClient::RefreshToken: " + RefreshToken);
                Debug.Log("UnityAuthClient::IdentityToken: " + IdentityToken);
                Debug.Log("UnityAuthClient::AccessTokenExpiration: " + AccessTokenExpiration);
                Debug.Log("UnityAuthClient::Signed in.");
                return(true);
            }

            return(false);
        }
コード例 #27
0
        private static int DecryptKeyChain(string[] args)
        {
            CommandLine cmdLine = new CommandLine(args, false);
            string      inPath  = cmdLine.GetOption("in", null);
            string      outPath = cmdLine.GetOption("out", null);
            string      key     = cmdLine.GetOption("key", null);
            KeyChain    keyChain;

            byte[] encrypted;

            if (inPath == null)
            {
                Program.Error("[-in:<path>] command line option is required.");
                return(1);
            }

            if (outPath == null)
            {
                Program.Error("[-out:<path>] command line option is required.");
                return(1);
            }

            if (key == null)
            {
                Program.Error("[-key:<symkey>] command line option is required.");
                return(1);
            }

            using (var input = new FileStream(inPath, FileMode.Open, FileAccess.Read))
            {
                encrypted = new byte[(int)input.Length];
                input.Read(encrypted, 0, encrypted.Length);
            }

            keyChain = new KeyChain(new SymmetricKey(key), encrypted);

            using (var output = new StreamWriter(outPath, false, Helper.AnsiEncoding))
            {
                var keys = keyChain.ToArray();

                for (int i = 0; i < keys.Length; i++)
                {
                    output.WriteLine(keys[i]);
                }
            }

            return(0);
        }
コード例 #28
0
        // Get keyChains from Seed data in DataBaseInitializer.

        public async Task <ActionResult> Details(int?id)
        {
            if (id == null)
            {
                // Returns a bad request message if strin is empty or null.

                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            KeyChain keyChain = await db.KeyChains.FindAsync(id);

            if (keyChain == null)
            {
                return(HttpNotFound());
            }
            return(View(keyChain));
        }
コード例 #29
0
        static void Main(string[] args)
        {
            var face = new Face
                           (new TcpTransport(), new TcpTransport.ConnectionInfo("localhost"));

            // For now, when setting face.setCommandSigningInfo, use a key chain with
            //   a default private key instead of the system default key chain. This
            //   is OK for now because NFD is configured to skip verification, so it
            //   ignores the system default key chain.
            var identityStorage   = new MemoryIdentityStorage();
            var privateKeyStorage = new MemoryPrivateKeyStorage();
            var keyChain          = new KeyChain
                                        (new IdentityManager(identityStorage, privateKeyStorage),
                                        new SelfVerifyPolicyManager(identityStorage));

            keyChain.setFace(face);

            // Initialize the storage.
            var keyName         = new Name("/testname/DSK-123");
            var certificateName = keyName.getSubName(0, keyName.size() - 1).append
                                      ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0");

            identityStorage.addKey(keyName, KeyType.RSA, new Blob(DEFAULT_RSA_PUBLIC_KEY_DER));
            privateKeyStorage.setKeyPairForKeyName
                (keyName, KeyType.RSA, new ByteBuffer(DEFAULT_RSA_PUBLIC_KEY_DER),
                new ByteBuffer(DEFAULT_RSA_PRIVATE_KEY_DER));

            face.setCommandSigningInfo(keyChain, certificateName);

            var echo   = new Echo(keyChain, certificateName);
            var prefix = new Name("/testecho");

            Console.Out.WriteLine("Register prefix  " + prefix.toUri());
            face.registerPrefix(prefix, echo, echo);

            // The main event loop.
            // Wait to receive one interest for the prefix.
            while (echo.responseCount_ < 1)
            {
                face.processEvents();

                // We need to sleep for a few milliseconds so we don't use 100% of
                //   the CPU.
                System.Threading.Thread.Sleep(5);
            }
        }
コード例 #30
0
    void Start()
    {
        // Find the player game object
        Player = (GameObject)GameObject.Find ("Player");

        // Find the keychain component
        if (Player)
        {
            PlayerKeyChain = Player.GetComponent<KeyChain>();
        }
        else
        {
            Debug.Log("No access to player");
        }

        OpenDoorPosition = transform.position + (transform.up*-5);
    }
コード例 #31
0
        void Save(Dictionary <string, string> data)
        {
            var serialized = JsonSerializer.Serialize(data);
            //var serializer = new DataContractJsonSerializer(typeof(Dictionary<string, string>));

            //var serialized = string.Empty;

            //using (var ms = new MemoryStream())
            //{
            //	serializer.WriteObject(ms, data);
            //	serialized = Encoding.Default.GetString(ms.ToArray());
            //}

            var kc = new KeyChain();

            kc.SetValueForKey(serialized, PREFERENCES_KEY);
        }
コード例 #32
0
        public ActionResult Index()
        {
            KeyChain keyChain = new KeyChain()
            {
                Color    = "",
                EndType  = "",
                Engraved = ""
            };

            var X = new Context();

            X.KeyChains.Add(keyChain);
            X.SaveChanges();


            return(View(keyChain));
        }
コード例 #33
0
ファイル: NdnBle.cs プロジェクト: remap/ice-ar
        onData(Interest interest, Data data)
        {
            //logTextBox.text += "\n" + "Got a status data packet with name " + data.getName().toUri();

            if (KeyChain.verifyDataWithHmacWithSha256(data, new Blob(hmacKey)))
            {
                //logTextBox.text += "\n" + "Successfully verified data";
            }
            else
            {
                logTextBox.text += "\n" + "Failed to verify incoming data packet, ignoring it...";
                logTextBox.text += "\n" + "Data name: " + data.getName().ToString();
            }

            var content       = data.getContent().buf();
            var contentString = "";

            for (int i = content.position(); i < content.limit(); ++i)
            {
                contentString += (char)content.get(i);
            }
            logTextBox.text += "\n" + "Data name: " + data.getName().ToString();
            logTextBox.text += "\n" + "Data content:";
            logTextBox.text += "\n" + "-------------";
            logTextBox.text += "\n" + contentString;
            logTextBox.text += "\n" + "---------------------------------";
            logTextBox.text += "\n";

            mNotifyScript.updateBeaconListText(contentString);

            if (!contentString.Equals(lastDataContent))
            {
                mNotifyScript.notifyUserOfBeaconListChange();
            }

            Interest statusInterest = new Interest(interest.getName());

            statusInterest.setInterestLifetimeMilliseconds(2000);

            var onStatusData    = new onStatusDataClass(logTextBox, mNotifyScript, mFace);
            var onStatusTimeout = new onStatusTimeoutClass(logTextBox, mFace, mNotifyScript);

            mFace.expressInterest(statusInterest, onStatusData, onStatusTimeout);

            lastDataContent = contentString;
        }
コード例 #34
0
    // Use this for initialization
    public void start()
    {
        face_ = new Face(new TcpTransport(), new TcpTransport.ConnectionInfo(hostName));

        bootstrap_       = new Bootstrap(face_);
        keyChain_        = bootstrap_.setupDefaultIdentityAndRoot(new Name(instanceName), new Name());
        certificateName_ = bootstrap_.getDefaultCertificateName();

        // initialize the gyro instance
        startOptConsumer();
        initialHandler_ = new InitialDataHandler(this);

        while (true)
        {
            face_.processEvents();
            System.Threading.Thread.Sleep(5);
        }
    }
コード例 #35
0
        private static MTProtoClientBuilder CreateDefault()
        {
            var clientTransportFactory = new ClientTransportFactory();
            var tlRig = new TLRig();
            var messageIdGenerator = new MessageIdGenerator();
            var hashServices = new HashServices();
            var encryptionServices = new EncryptionServices();
            var randomGenerator = new RandomGenerator();
            var messageCodec = new MessageCodec(tlRig, hashServices, encryptionServices, randomGenerator);
            var keyChain = new KeyChain(tlRig, hashServices);
            var nonceGenerator = new NonceGenerator();

            return new MTProtoClientBuilder(clientTransportFactory,
                tlRig,
                messageIdGenerator,
                messageCodec,
                hashServices,
                encryptionServices,
                nonceGenerator,
                keyChain);
        }