Beispiel #1
0
        static void Main(string[] args)
        {
            try
            {
                Logger.Initialize();

                byte[] data = "Hello world".GetBytes();

                SignKeys signKeys = DataSigner.GenerateSignKeyPair();

                byte[] signature = DataSigner.Sign(data, signKeys.PublicAndPrivate);

                bool valid = DataSigner.IsSignatureValid(data, signature, signKeys.PublicOnly);
                Console.WriteLine(valid ? "Valid" : "NOT Valid");

                data[0] = 41;

                valid = DataSigner.IsSignatureValid(data, signature, signKeys.PublicOnly);
                Console.WriteLine(valid ? "Valid" : "NOT Valid");

                data[0] = "H".GetBytes()[0];

                valid = DataSigner.IsSignatureValid(data, signature, signKeys.PublicOnly);
                Console.WriteLine(valid ? "Valid" : "NOT Valid");
            }
            catch (Exception e)
            {
                Logger.LogError("Unhandled exception", e);
                Console.WriteLine("Error: " + e.Message);
            }

            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
        }
Beispiel #2
0
        public bool VerifyIntegrity(Guid userId, Guid dataEntityId)
        {
            AssertSystemIsInitialized();

            User user = GetAssertUser(userId);

            IList <Role> roles = this.storage.GetRolesForUser(user.Id);

            bool userHasRoleWhichHasDataEntity = roles.Any(role => role.DataEntities.Contains(dataEntityId));

            if (!userHasRoleWhichHasDataEntity)
            {
                throw new InvalidOperationException("You do not have a role which gives access to the requested data entity");
            }


            DataEntity dataEntity = this.storage.GetDataEntityFromId(dataEntityId);

            if (dataEntity == null)
            {
                throw new InvalidOperationException("Data entity with specified id was not found");
            }

            Guid authorId = this.storage.GetAuthorOfDataEntity(dataEntityId);

            User authoringUser = this.storage.GetUser(authorId);

            dataEntity.Payload.Content = this.storage.GetDataEntityPayloadFromId(dataEntityId);

            return(DataSigner.IsSignatureValid(dataEntity, dataEntity.Signature, authoringUser.SignPublicKey));
        }
Beispiel #3
0
        public void Insert(Guid userId, DataEntity dataEntity)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("userId");
            }
            CheckDataEntity(dataEntity);

            GetDelegationKey(userId);   // check that the user has a key (is still valid)

            byte[] signPublicKey = this.tokenStorage.FindSignPublicKey(userId);
            if (signPublicKey == null)
            {
                throw new InvalidOperationException("Cannot insert data as no sign key is registered for the user");
            }

            if (!DataSigner.IsSignatureValid(dataEntity, dataEntity.Signature, signPublicKey))
            {
                throw new InvalidOperationException("The data signature is not valid");
            }

            // TODO: check access rights)

            this.dataEntityStorage.InsertDataEntity(userId, dataEntity);
        }
Beispiel #4
0
        private void buttonGenerateAndSaveMasterKeypair_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.textBoxDOUsername.Text))
                {
                    MessageBox.Show("You must enter a DO user name");
                    return;
                }

                if (string.IsNullOrEmpty(this.textBoxDORoleName.Text))
                {
                    MessageBox.Show("You must enter a DO role name");
                    return;
                }

                IPreService proxy = GetPreProxy();
                this.masterKeypair = proxy.GenerateKeyPair();

                SignKeys doSignKeyPair = DataSigner.GenerateSignKeyPair();

                proxy = GetPreProxy();
                byte[] doUserName = proxy.Encrypt(this.masterKeypair.Public, this.textBoxDOUsername.Text.GetBytes());

                proxy = GetPreProxy();
                byte[] doRoleName = proxy.Encrypt(this.masterKeypair.Public, this.textBoxDORoleName.Text.GetBytes());


                IGatewayService gwProxy = GetServiceProxy();
                gwProxy.InitializeSystem(this.myId, doUserName, doRoleName, doSignKeyPair.PublicOnly);

                string filename = FileDialogs.AskUserForFileNameToSaveIn();
                if (!string.IsNullOrEmpty(filename))
                {
                    if (!Path.HasExtension(filename))
                    {
                        filename = filename + ".xml";
                    }

                    KeyCollection keys = new KeyCollection();
                    keys.MasterPublicKey  = Convert.ToBase64String(this.masterKeypair.Public);
                    keys.MasterPrivateKey = Convert.ToBase64String(this.masterKeypair.Private);
                    keys.PrivateKey       = keys.MasterPrivateKey;
                    keys.PublicKey        = keys.MasterPublicKey;
                    keys.SignKeys         = Convert.ToBase64String(doSignKeyPair.PublicAndPrivate);

                    XmlFile.WriteFile(keys, filename);

                    this.labelKeyStatus.Text = "Keys including MASTER KEYS loaded";

                    MessageBox.Show("Done");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                Logger.LogError("Error generating master keypair", ex);
            }
        }
Beispiel #5
0
        private void buttonUploadNow_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listBoxUploadKeywords.Items.Count == 0)
                {
                    MessageBox.Show("At least one keyword must be associated with the data before it is uploaded");
                    return;
                }
                if (this.keyPair == null)
                {
                    MessageBox.Show("You must load user keys first");
                    return;
                }

                if (this.rolesUserControlUploadData.SelectedRoles.Count == 0)
                {
                    MessageBox.Show("You must select at least one role which should have access to the uploaded data");
                    return;
                }

                byte[] fileContent = File.ReadAllBytes(this.labelUploadData.Text);

                AesEncryptionInfo encryptionInfo = SymmetricEncryptor.GenerateSymmetricKeyInfo();

                byte[] fileCiphertext = SymmetricEncryptor.Encrypt(fileContent, encryptionInfo);

                IPreService preProxy = CreatePreProxy();
                byte[]      encSymIv = preProxy.Encrypt(this.keyPair.Public, encryptionInfo.IV);

                preProxy = CreatePreProxy();
                byte[] encSymKey = preProxy.Encrypt(this.keyPair.Public, encryptionInfo.Key);

                byte[] name = SymmetricEncryptor.Encrypt(Path.GetFileName(this.labelUploadData.Text).GetBytes(), encryptionInfo);

                DataEntity entity = new DataEntity();
                entity.Attributes = CollectAndEncryptAttributes(encryptionInfo);
                entity.Payload    = new FilePayload(name, fileCiphertext);
                entity.AesInfo    = new AesEncryptionInfo(encSymKey, encSymIv);
                entity.Id         = Guid.NewGuid();

                entity.Signature = DataSigner.Sign(entity, this.signingKeys);

                IGatewayService proxy = CreateServiceProxy();

                proxy.CreateDataEntities(this.myId, this.rolesUserControlUploadData.SelectedRoles, new[] { entity });

                MessageBox.Show("Done uploading");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                Logger.LogError("Error preparing and uploading data to server", ex);
            }
        }
Beispiel #6
0
        private void buttonGenerateKeypairsForUser_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.textBoxNewUserId.Text))
                {
                    MessageBox.Show("You must enter a username");
                    return;
                }
                this.newUserId = GuidCreator.CreateGuidFromString(this.textBoxNewUserId.Text);

                if (this.masterKeypair == null)
                {
                    MessageBox.Show("You must load master key pair first");
                    return;
                }

                string filename = FileDialogs.AskUserForFileNameToSaveIn();
                if (!string.IsNullOrEmpty(filename))
                {
                    if (!Path.HasExtension(filename))
                    {
                        filename = filename + ".xml";
                    }


                    this.signKeyPair = DataSigner.GenerateSignKeyPair();

                    IPreService proxy = GetPreProxy();
                    this.userKeypair = proxy.GenerateKeyPair();

                    proxy = GetPreProxy();
                    this.delegationToken.ToUser = proxy.GenerateDelegationKey(this.masterKeypair.Private, this.userKeypair.Public);

                    IGatewayService gateWayproxy = GetServiceProxy();
                    gateWayproxy.RegisterUser(this.myId, this.newUserId, this.delegationToken, this.signKeyPair.PublicOnly);


                    UserKeys uk = new UserKeys();
                    uk.MasterKeyPublicKey = Convert.ToBase64String(this.masterKeypair.Public);
                    uk.UserPrivateKey     = Convert.ToBase64String(this.userKeypair.Private);
                    uk.UserSignKeys       = Convert.ToBase64String(this.signKeyPair.PublicAndPrivate);

                    XmlFile.WriteFile(uk, filename);

                    MessageBox.Show("Done");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                Logger.LogError("Error generating user keypair", ex);
            }
        }
Beispiel #7
0
        public void CreateDataEntities(Guid userId, IList <Guid> roleIds, IList <DataEntity> dataEntities)
        {
            if (dataEntities == null)
            {
                throw new ArgumentNullException("dataEntities");
            }
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("userId");
            }

            AssertSystemIsInitialized();

            User user = GetAssertUser(userId);

            IList <Role> checkedRoles = new List <Role>();

            foreach (Guid roleId in roleIds)
            {
                Role r = GetAssertRole(roleId);

                AssertUserHasRoleOrAncestorOfRole(user, roleId);

                if (r.DataEntityPermission == DataEntityPermission.ReadContent)
                {
                    throw new InvalidOperationException("You cannot create data using one of the specified roles");
                }

                checkedRoles.Add(r);
            }

            AssertRolesHasSameRoot(checkedRoles);

            foreach (DataEntity dataEntity in dataEntities)
            {
                CheckDataEntity(dataEntity);

                if (!DataSigner.IsSignatureValid(dataEntity, dataEntity.Signature, user.SignPublicKey))
                {
                    throw new InvalidOperationException("A data signature is not valid");
                }
            }

            foreach (DataEntity entity in dataEntities)
            {
                this.storage.CreateDataEntity(userId, entity);
            }

            foreach (Role role in checkedRoles)
            {
                AddDataEntitiesToRoleAndAllParentsRoles(this.storage.GetDataOwnerRole(), role, dataEntities);
            }
        }
Beispiel #8
0
        private void buttonUploadNow_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listBoxUploadKeywords.Items.Count == 0)
                {
                    MessageBox.Show("At least one keyword must be associated with the data before it is uploaded");
                    return;
                }
                if (!this.userkeysLoaded)
                {
                    MessageBox.Show("You must load user keys first");
                    return;
                }

                byte[] fileContent = File.ReadAllBytes(this.labelUploadData.Text);

                AesEncryptionInfo encryptionInfo = SymmetricEncryptor.GenerateSymmetricKeyInfo();

                byte[] fileCiphertext = SymmetricEncryptor.Encrypt(fileContent, encryptionInfo);

                IPreService preProxy = CreatePreProxy();
                byte[]      encSymIv = preProxy.Encrypt(this.masterPublicKey, encryptionInfo.IV);

                preProxy = CreatePreProxy();
                byte[] encSymKey = preProxy.Encrypt(this.masterPublicKey, encryptionInfo.Key);

                byte[] name = SymmetricEncryptor.Encrypt(Path.GetFileName(this.labelUploadData.Text).GetBytes(), encryptionInfo);

                DataEntity entity = new DataEntity();
                entity.Attributes = CollectAndEncryptAttributes(encryptionInfo);
                entity.Payload    = new FilePayload(name, fileCiphertext);
                entity.AesInfo    = new AesEncryptionInfo(encSymKey, encSymIv);
                entity.Id         = Guid.NewGuid(); // perhaps base guid on the file path??

                entity.Signature = DataSigner.Sign(entity, this.userSignKeys);

                IGatewayService proxy = CreateServiceProxy();

                proxy.InsertData(GetUserIdentity(), entity);

                MessageBox.Show("Done uploading");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                Logger.LogError("Error preparing and uploading data to server", ex);
            }
        }
Beispiel #9
0
        public bool VerifyIntegrity(Guid userId, Guid dataEntityId)
        {
            GetDelegationKey(userId); // to check that the user is still valid and has not been revoked

            DataEntity dataEntity = this.dataEntityStorage.FindDataEntityMetadataFromId(dataEntityId);

            if (dataEntity == null)
            {
                throw new InvalidOperationException("Data entity with specified id was not found");
            }

            Guid authorId = this.dataEntityStorage.FindAuthorOfDataEntity(dataEntityId);

            byte[] signPublicKey = this.tokenStorage.FindSignPublicKey(authorId);

            dataEntity.Payload.Content = this.dataEntityStorage.FindDataEntityPayloadFromId(dataEntityId);

            return(DataSigner.IsSignatureValid(dataEntity, dataEntity.Signature, signPublicKey));
        }
Beispiel #10
0
        private void buttonCreateUser_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.treeViewRoles.SelectedNode == null ||
                    !(this.treeViewRoles.SelectedNode.Tag is RoleDescription))
                {
                    return;
                }

                if (string.IsNullOrEmpty(this.textBoxNewUserName.Text))
                {
                    MessageBox.Show("You must enter a username");
                    return;
                }
                Guid newUserId = GuidCreator.CreateGuidFromString(this.textBoxNewUserName.Text);

                if (this.masterKeypair == null && this.keyPair == null)
                {
                    MessageBox.Show("You must load your key pair first");
                    return;
                }

                string filename = FileDialogs.AskUserForFileNameToSaveIn();
                if (!string.IsNullOrEmpty(filename))
                {
                    if (!Path.HasExtension(filename))
                    {
                        filename = filename + ".xml";
                    }

                    SignKeys        userSignKeyPair = DataSigner.GenerateSignKeyPair();
                    IPreService     proxy;
                    KeyPair         userKeypair;
                    DelegationToken userDelegationToken;

                    if (this.masterKeypair != null)
                    {
                        proxy       = GetPreProxy();
                        userKeypair = proxy.GenerateKeyPair();

                        userDelegationToken = new DelegationToken();
                        proxy = GetPreProxy();
                        userDelegationToken.ToUser = proxy.GenerateDelegationKey(this.masterKeypair.Private, userKeypair.Public);
                    }
                    else
                    {
                        userKeypair         = this.keyPair; // I am not a DO, so when creating a new user then reuse my key
                        userDelegationToken = null;         // I do not know my own delegation key. The server will put it in for me.
                    }

                    proxy = GetPreProxy();
                    byte[] username = proxy.Encrypt(this.keyPair.Public, this.textBoxNewUserName.Text.GetBytes());

                    User user = new User();
                    user.DelegationToken = userDelegationToken;
                    user.Id            = newUserId;
                    user.Name          = username;
                    user.SignPublicKey = userSignKeyPair.PublicOnly;


                    RoleDescription role         = (RoleDescription)this.treeViewRoles.SelectedNode.Tag;
                    IGatewayService gateWayproxy = GetServiceProxy();
                    gateWayproxy.CreateUser(this.myId, role.Id, user);


                    KeyCollection uk = new KeyCollection();
                    uk.PublicKey  = Convert.ToBase64String(this.keyPair.Public); // use original DO public key
                    uk.PrivateKey = Convert.ToBase64String(userKeypair.Private);
                    uk.SignKeys   = Convert.ToBase64String(userSignKeyPair.PublicAndPrivate);

                    XmlFile.WriteFile(uk, filename);

                    buttonRefreshRolesAndUsers_Click(this, EventArgs.Empty);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                Logger.LogError("Error generating user keypair", ex);
            }
        }