示例#1
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok && data != null)
            {
                if (requestCode == CHOOSE_TRUST_CHAIN_FILE)
                {
                    var fullPath = data.Data.Path;

                    byte[] trustChainBytes = File.ReadAllBytes(fullPath);

                    try {
                        TrustChainNode[] nodes = TrustChainUtil.SegmentChain(trustChainBytes);

                        if (TrustChainUtil.ValidateTrustChain(nodes))
                        {
                            identity.AddTrustChain(trustChainBytes);
                        }
                        else
                        {
                            Toast.MakeText(this, "Could not validate the trust chain", ToastLength.Short).Show();
                        }
                    } catch (CryptographicException) {
                        Toast.MakeText(this, "Could not validate the trust chain", ToastLength.Short).Show();
                    }
                }
                else if (requestCode == CHOOSE_IDENTITY_FILE)
                {
                    var fullPath = data.Data.Path;
                    Console.WriteLine($"got path {fullPath}");

                    byte[] newIdentity = File.ReadAllBytes(fullPath);

                    if (newIdentity.Length != CryptoUtil.ASYM_KEY_SIZE_BYTES)
                    {
                        Toast.MakeText(this, "Identity is invalid length", ToastLength.Short).Show();
                    }
                    else
                    {
                        // TODO add changeable permissions
                        var newChainBytes = identity.GenerateNewChain(newIdentity, identity.PermissionsHeld,
                                                                      identity.PermissionsGrantable, "Child");

                        var trustChainFileName = string.Format(TRUST_CHAIN_FORMAT_STRING,
                                                               IdentityManager.GetIdentityString(newIdentity));
                        var trustChainFullPath = Path.Combine(privatePath, trustChainFileName);
                        File.WriteAllBytes(trustChainFullPath, newChainBytes);

                        startEmail("Trust chain", trustChainFullPath);
                    }
                }
            }
        }
示例#2
0
        public object ToObject(byte[] buffer)
        {
            using (var ms = new MemoryStream(buffer))
                using (var reader = new BinaryReader(ms)) {
                    var packetType = (PacketType)reader.ReadUInt32();
                    switch (packetType)
                    {
                    case PacketType.Have:
                        return(new HavePacket {
                            MerkleRootHash = reader.ReadSha256Base64()
                        });

                    case PacketType.Need:
                        return(new NeedPacket {
                            MerkleRootHash = reader.ReadSha256Base64()
                        });

                    case PacketType.Give:
                        return(new GivePacket {
                            NodeHash = reader.ReadSha256Base64(),
                            Node = reader.ReadMerkleNode()
                        });

                    case PacketType.Whois:
                        return(new WhoisPacket {
                            IdHash = reader.ReadBytes(CryptoUtil.HASH_SIZE)
                        });

                    case PacketType.Ident:
                        return(new IdentPacket {
                            Id = reader.ReadBytes(CryptoUtil.ASYM_KEY_SIZE_BYTES),
                            TrustChain = TrustChainUtil.SegmentChain(reader.ReadBytes(reader.ReadInt32() * TrustChainNode.NODE_BLOCK_SIZE))
                        });

                    case PacketType.Done:
                        return(new DonePacket());

                    default:
                        throw new InvalidStateException();
                    }
                }
        }
示例#3
0
        public void Setup()
        {
            var nativeBluetoothAdapter = BluetoothAdapter.DefaultAdapter;

            if (!nativeBluetoothAdapter.IsEnabled)
            {
                System.Console.WriteLine("Enabling bluetooth");
                Intent enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
                StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                return;
            }

            var androidBluetoothAdapter = new AndroidBluetoothAdapterFactory().Create(this, ApplicationContext, nativeBluetoothAdapter);
            var client = CampfireNetClientBuilder.CreateNew()
                         .WithDevelopmentNetworkClaims()
                         .WithBluetoothAdapter(androidBluetoothAdapter)
                         .Build();
            var identity = client.Identity;

            var sync = new object();

            client.MessageReceived += e => {
                lock (sync) {
                    var s = Encoding.UTF8.GetString(e.Message.DecryptedPayload, 0, e.Message.DecryptedPayload.Length);
                    uiDispatchHandler.ObtainMessage(LOG_MESSAGE, "RECV: " + s).SendToTarget();
                }
            };


            generateButton.Click += (s, e) => {
                var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                path = Path.Combine(path, $"trust_chain_{IdentityManager.GetIdentityString(identity.PublicIdentityHash)}.bin");

                if (!File.Exists(path) && identity.TrustChain == null)
                {
                    identity.GenerateRootChain();

                    using (var stream = new FileStream(path, FileMode.Create))
                        using (var writer = new BinaryWriter(stream)) {
                            writer.Write(TrustChainUtil.SerializeTrustChain(identity.TrustChain));
                        }
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Trust chain already exists.", ToastLength.Short).Show();
                }
            };

            sendButton.Click += (s, e) => {
                var filename = $"trust_chain_{IdentityManager.GetIdentityString(identity.PublicIdentityHash)}.bin";
                var path     = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                path = Path.Combine(path, filename);

                // TODO fix
                if (!File.Exists(path))
                {
                    Toast.MakeText(ApplicationContext, "Cannot find file in Download folder.", ToastLength.Short).Show();
                    return;
                }

                var tmpFolder = Environment.ExternalStorageDirectory.ToString();
                var tmpFile   = Path.Combine(tmpFolder, filename);
                File.Copy(path, tmpFile, true);

                var file = new Java.IO.File(tmpFile);
                var uri  = Android.Net.Uri.FromFile(file);

                Intent email = new Intent(Intent.ActionSend);
                email.SetType("message/rfc822");
                email.PutExtra(Intent.ExtraSubject, "Trust chain addition");
                email.PutExtra(Intent.ExtraStream, uri);
                email.AddFlags(ActivityFlags.GrantReadUriPermission);

                try {
                    StartActivityForResult(Intent.CreateChooser(email, "Send mail with: "), 0);
                } catch (ActivityNotFoundException) {
                    Toast.MakeText(ApplicationContext, "There are no email clients installed.", ToastLength.Short).Show();
                }
            };

            loadButton.Click += (s, e) => {
                var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                path = Path.Combine(path, $"trust_chain_{IdentityManager.GetIdentityString(identity.PublicIdentityHash)}.bin");

                if (!File.Exists(path))
                {
                    Toast.MakeText(ApplicationContext, "Cannot find own trust chain file in Download folder.", ToastLength.Short).Show();
                    return;
                }

                byte[] data = File.ReadAllBytes(path);

                try {
                    identity.AddTrustChain(data);
                    Toast.MakeText(ApplicationContext, "Successfully loaded trust chain.", ToastLength.Short).Show();
                } catch (BadTrustChainException) {
                    Toast.MakeText(ApplicationContext, "Invalid trust chain found.", ToastLength.Short).Show();
                }
            };

            clearButton.Click += (s, e) => {
                var privateFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                var files         = Directory.GetFiles(privateFolder);

                foreach (var file in files)
                {
                    File.Delete(file);
                }

                //var path = Path.Combine(privateFolder, PRIVATE_KEY_FILE);
                //identity.SaveKey(path);
            };


            sendTextButton.Click += (s, e) => {
                var text = inputText.Text;
                client.BroadcastAsync(Encoding.UTF8.GetBytes(text)).Forget();
                inputText.Text = "";
            };

            client.RunAsync().Forget();
        }
示例#4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Settings);

            toolbar = FindViewById <Toolbar>(Resource.Id.Toolbar);
            SetActionBar(toolbar);
            ActionBar.SetDisplayHomeAsUpEnabled(true);

            becomeRoot     = FindViewById <LinearLayout>(Resource.Id.BecomeRoot);
            loadTrustChain = FindViewById <LinearLayout>(Resource.Id.LoadChain);
            inviteFriend   = FindViewById <LinearLayout>(Resource.Id.Invite);
            sendId         = FindViewById <LinearLayout>(Resource.Id.SendId);
            clearAllKnown  = FindViewById <LinearLayout>(Resource.Id.ClearAll);


            prefs = Application.GetSharedPreferences("CampfireChat", FileCreationMode.Private);

            identity    = Globals.CampfireNetClient.Identity;
            privatePath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

            becomeRoot.Click += (sender, e) => {
                var fileName = string.Format(TRUST_CHAIN_FORMAT_STRING,
                                             IdentityManager.GetIdentityString(identity.PublicIdentityHash));
                var fullPath = Path.Combine(privatePath, fileName);

                if (!File.Exists(fullPath) && identity.TrustChain == null)
                {
                    identity.GenerateRootChain();

                    byte[] trustChainBytes = TrustChainUtil.SerializeTrustChain(identity.TrustChain);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                        using (var writer = new BinaryWriter(stream)) {
                            writer.Write(trustChainBytes);
                        }
                    Toast.MakeText(ApplicationContext, "Root node successfully created", ToastLength.Short).Show();
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Trust chain already exists", ToastLength.Short).Show();
                }
            };

            loadTrustChain.Click += (sender, e) => {
                Intent chooseFile = new Intent(Intent.ActionGetContent);
                chooseFile.AddCategory(Intent.CategoryOpenable);
                chooseFile.SetType("text/plain");
                chooseFile = Intent.CreateChooser(chooseFile, "Choose a trust chain file to load");

                Toast.MakeText(ApplicationContext, "Choose a trust chain file to load (*.tc)", ToastLength.Short).Show();

                StartActivityForResult(chooseFile, CHOOSE_TRUST_CHAIN_FILE);
            };

            inviteFriend.Click += (sender, e) => {
                Intent chooseFile = new Intent(Intent.ActionGetContent);
                chooseFile.AddCategory(Intent.CategoryOpenable);
                chooseFile.SetType("text/plain");
                chooseFile = Intent.CreateChooser(chooseFile, "Choose an identity to load");

                Toast.MakeText(ApplicationContext, "Choose an identity to load (*.id)", ToastLength.Short).Show();

                StartActivityForResult(chooseFile, CHOOSE_IDENTITY_FILE);
            };

            sendId.Click += (sender, e) => {
                var idBytes = identity.PublicIdentity;

                var idFileName = string.Format(IDENTITY_FORMAT_STRING, IdentityManager.GetIdentityString(idBytes));
                var idFullPath = Path.Combine(privatePath, idFileName);
                File.WriteAllBytes(idFullPath, idBytes);

                startEmail("Identification", idFullPath);
            };

            clearAllKnown.Click += (sender, e) => {
                foreach (var file in Directory.GetFiles(privatePath))
                {
                    if (file.EndsWith(".tc", StringComparison.Ordinal) || file.EndsWith(".id", StringComparison.Ordinal))
                    {
                        File.Delete(file);
                        Console.WriteLine($"deleting {file}");
                    }
                }
            };
        }