public void WhenPublicKeyIsNullhenShouldThrowArgumentException()
        {
            byte[] data    = { 10, 47, 67, 10, 91, 15, 33, 25 };
            int    keySize = 2048;

            Assert.ThrowsException <ArgumentNullException>(() => AsymmetricCryptoUtil.Encrypt(data, keySize, null));
        }
        public void WhenByteArrayAndKeyIsNullAndDrecryptThenShouldThrowArgumentNullException()
        {
            byte[] data    = { 10, 47, 67, 10, 91, 15, 33, 25 };
            int    keySize = 1024;

            Assert.ThrowsException <ArgumentNullException>(() => AsymmetricCryptoUtil.Decrypt(data, keySize, null));
        }
        public void WhenGeneratingKeysAreOutOfRangeThenShouldThrowException()
        {
            int keySize = int.MaxValue;

            Assert.ThrowsException <ArgumentOutOfRangeException>(() =>
            {
                AsymmetricCryptoUtil.GenerateKeys(keySize, out string publicKey, out string publicAndPrivateKey);
            });
        }
Esempio n. 4
0
        public void GenerateKeyPairUnsupported()
        {
            // Ensure we have the correct first value of the enum.
            Assert.AreEqual((double)KeyPair.KeyTypes.Ecc, 0);

            const KeyPair.KeyTypes invalidEnumType = KeyPair.KeyTypes.Ecc - 1;

            Assert.Throws <InvalidEnumArgumentException>(() => AsymmetricCryptoUtil.GenerateKeyPair(invalidEnumType));
        }
Esempio n. 5
0
        public void GenerateKeyPairEcc()
        {
            // Generation of a keyPair is non-deterministic, so we'll perform some extra checks to be sure.
            var keyPair = AsymmetricCryptoUtil.GenerateKeyPair(KeyPair.KeyTypes.Ecc);

            Assert.IsNotEmpty(keyPair.PrivatePem);
            Assert.IsNotEmpty(keyPair.PublicPem);
            Assert.IsTrue(VerifyKeyPairSignatures(TestString, keyPair.PrivatePem, keyPair.PublicPem));
        }
        public void WhenDataToEncryptIsNullThenShouldThrowArgumentNullException()
        {
            int    keySize = 1024;
            string publicKey;
            string publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            Assert.ThrowsException <ArgumentNullException>(() => AsymmetricCryptoUtil.Encrypt(null, keySize, publicKey));
        }
        public void WhenDataToEncryptIsEmptyAndRSAParametersThenShouldThrowArgumentNullException()
        {
            int           keySize = 1024;
            RSAParameters publicKey;
            RSAParameters publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            Assert.ThrowsException <ArgumentNullException>(() => AsymmetricCryptoUtil.Encrypt(new byte[] { }, keySize, publicKey));
        }
        public void WhenByteArrayIsNullAndRSAParametersDrecryptThenShouldThrowArgumentNullException()
        {
            int           keySize = 1024;
            RSAParameters publicKey;
            RSAParameters publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            Assert.ThrowsException <ArgumentNullException>(() => AsymmetricCryptoUtil.Decrypt(null, keySize, publicAndPrivateKey));
        }
        public void WhenByteArrayKeyIsOutOfRangeAndDecryptAndRSAParametersThenShouldThrowArgumentNullException()
        {
            byte[]        data    = { 10, 47, 67, 10, 91, 15, 33, 25 };
            int           keySize = 1024;
            RSAParameters publicKey;
            RSAParameters publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            Assert.ThrowsException <ArgumentOutOfRangeException>(() => AsymmetricCryptoUtil.Decrypt(data, int.MaxValue, publicAndPrivateKey));
        }
        public void WhenKeySizeIsGreaterThanMaxValueThenShouldThrowArgumentException()
        {
            byte[] data    = { 10, 47, 67, 10, 91, 15, 33, 25 };
            int    keySize = 4096;
            string publicKey;
            string publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            Assert.ThrowsException <ArgumentOutOfRangeException>(() => AsymmetricCryptoUtil.Encrypt(data, int.MaxValue, publicKey));
        }
        public void WhenByteArrayIsEmptyAndRSAParametersDrecryptThenShouldThrowArgumentNullException()
        {
            byte[]        data    = { 10, 47, 67, 10, 91, 15, 33, 25 };
            int           keySize = 1024;
            RSAParameters publicKey;
            RSAParameters publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            Assert.ThrowsException <ArgumentNullException>(() => AsymmetricCryptoUtil.Decrypt(new byte[] { }, keySize, publicAndPrivateKey));
        }
        public void WhenDataSizeIsGreaterThanMaximumAllowedForKeyAndRSAParametersThenShouldThrowArgumentException()
        {
            int keySize = 384;

            byte[] data = new byte[AsymmetricCryptoUtil.GetMaxDataLength(384) * 2];

            Random random = new Random();

            random.NextBytes(data);

            AsymmetricCryptoUtil.GenerateKeys(keySize, out RSAParameters publicKey, out RSAParameters publicAndPrivateKey);

            Assert.ThrowsException <ArgumentOutOfRangeException>(() => AsymmetricCryptoUtil.Encrypt(data, keySize, publicKey));
        }
        public void WhenTextIsProvidedThenShouldBeAbleToEncryptAndDecryptTest()
        {
            string data    = "Essa é uma string de teste para testar a criptografia assimétrica utilizando RSA.";
            int    keySize = 4096;
            string publicKey;
            string publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            var encryptedData = AsymmetricCryptoUtil.EncryptText(data, keySize, publicKey);

            var decryptedData = AsymmetricCryptoUtil.DecryptText(encryptedData, keySize, publicAndPrivateKey);

            Assert.AreNotEqual(data, encryptedData);
            Assert.AreEqual(data, decryptedData);
        }
        public void WhenByteArrayIsProvidedAndRSAParameterKeysThenShouldBeAbleToEncryptAndDecryptTest()
        {
            byte[]        data    = { 10, 47, 67, 10, 91, 15, 33, 25 };
            int           keySize = 1024;
            RSAParameters publicKey;
            RSAParameters publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            var encryptedData = AsymmetricCryptoUtil.Encrypt(data, keySize, publicKey);

            var decryptedData = AsymmetricCryptoUtil.Decrypt(encryptedData, keySize, publicAndPrivateKey);

            CollectionAssert.AreNotEqual(data, encryptedData);
            CollectionAssert.AreEqual(data, decryptedData);
        }
        public void WhenTextIsProvidedAndRSAParameterKeysThenShouldBeAbleToEncryptAndDecryptTest()
        {
            string        data    = "Test cryptographic RSA";
            int           keySize = 8192;
            RSAParameters publicKey;
            RSAParameters publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            var encryptedData = AsymmetricCryptoUtil.EncryptText(data, keySize, publicKey);

            var decryptedData = AsymmetricCryptoUtil.DecryptText(encryptedData, keySize, publicAndPrivateKey);

            Assert.AreNotEqual(data, encryptedData);
            Assert.AreEqual(data, decryptedData);
        }
        public void WhenGeneratingKeysThenPublicAndPrivateAndRSAParametersKeyMustBeDifferent()
        {
            int           keySize = 4096;
            RSAParameters publicKey;
            RSAParameters publicAndPrivateKey;

            AsymmetricCryptoUtil.GenerateKeys(keySize, out publicKey, out publicAndPrivateKey);

            Assert.AreNotEqual(string.Empty, publicKey);
            Assert.IsNotNull(publicKey);

            Assert.AreNotEqual(string.Empty, publicAndPrivateKey);
            Assert.IsNotNull(publicAndPrivateKey);

            Assert.AreNotEqual(publicKey, publicAndPrivateKey);
        }
        private void CheckLink()
        {
            var syncInstance = Controller.GetSyncServerInstance(_serverAccountId);

            var messageHandler = new VerifyDeviceKeysResponseHandler(
                Controller.GetSyncServerInstance(_serverAccountId), _nonce);

            // Give the sync process a kick up the arse
            syncInstance.ProcessMessagesOnly();

            var replyReceived = messageHandler.WaitForReply();

            // Tell the sync process to go back to normal duties
            syncInstance.ProcessMessagesOnlyStop();

            if (!replyReceived)
            {
                MessageBox.Show(@"Device verification timed out");
                if (!_formClosed)
                {
                    Invoke((MethodInvoker)Close);
                }
                return;
            }

            var secretShareMessage = messageHandler.Reply;

            if (!secretShareMessage.Verified)
            {
                MessageBox.Show(@"Device verification denied.");
                if (!_formClosed)
                {
                    Invoke((MethodInvoker)Close);
                }
                return;
            }

            // Verify the signature against the public key we have for it.
            var account = Model.ServerAccounts.Get(_serverAccountId);
            var linkedClientCryptoKey = Model.CryptoKeys.Get(account.LinkedDeviceCryptoKeyId);
            var signatureVerified     = AsymmetricCryptoUtil.VerifySignature(
                _nonce, messageHandler.Reply.NonceSigned, linkedClientCryptoKey.PublicKeyPem);

            if (!signatureVerified)
            {
                MessageBox.Show(@"Device verification failed.");
                messageHandler.MarkAsProcessed(false);
                if (!_formClosed)
                {
                    Invoke((MethodInvoker)Close);
                }
                return;
            }

            messageHandler.MarkAsProcessed(true);

            Model.CryptoKeys.Update(linkedClientCryptoKey.Id, new CryptoKey {
                Trust = true
            });

            Controller.UpdateHomePage();

            if (!_formClosed)
            {
                Invoke((MethodInvoker)Close);
            }
        }
Esempio n. 18
0
 public void CreateVerifySignatureUnsupported()
 {
     Assert.Throws <ArgumentException>(() => AsymmetricCryptoUtil.CreateSignature(TestString, DesPrivateKeyPem));
     Assert.Throws <ArgumentException>(() => AsymmetricCryptoUtil.VerifySignature(TestString, "", DesPublicKeyPem));
 }
 public void WhenKeySizeIs2048ThenShouldReturnMaxDataLength215()
 {
     Assert.AreEqual(215, AsymmetricCryptoUtil.GetMaxDataLength(2048));
 }
 public void WhenKeySizeIsOutOfRangeThenShouldThrowArgumentOutOfRangeException()
 {
     Assert.ThrowsException <ArgumentOutOfRangeException>(() => AsymmetricCryptoUtil.GetMaxDataLength(int.MaxValue));
 }
 public void WhenKeySizeIs4096ThenShouldReturnMaxDataLength471()
 {
     Assert.AreEqual(471, AsymmetricCryptoUtil.GetMaxDataLength(4096));
 }
Esempio n. 22
0
        private bool VerifyKeyPairSignatures(string message, string privateKeyPem, string publicKeyPem)
        {
            var signature = AsymmetricCryptoUtil.CreateSignature(message, privateKeyPem);

            return(AsymmetricCryptoUtil.VerifySignature(message, signature, publicKeyPem));
        }
 public void WhenKeySizeIsLessThan384ThenShouldReturnFalse()
 {
     Assert.IsFalse(AsymmetricCryptoUtil.IsKeySizeValid(376));
 }
 public void WhenKeySizeIsGreaterThan384ThenShouldReturnFalse()
 {
     Assert.IsFalse(AsymmetricCryptoUtil.IsKeySizeValid(16392));
 }
 public void WhenKeySizeIsInRangeAndMultipleOfEightThenShouldReturnTrue()
 {
     Assert.IsTrue(AsymmetricCryptoUtil.IsKeySizeValid(4096));
 }
 public void WhenKeySizeIsInRangeAndNotMultipleOfEightThenShouldReturnFalse()
 {
     Assert.IsFalse(AsymmetricCryptoUtil.IsKeySizeValid(4092));
 }
Esempio n. 27
0
        public bool RegisterInitialOtpDevice(string linkCodeString)
        {
            var linkCode   = new LinkCodeRegisterInitialOtpDevice(linkCodeString);
            var newKeyPair = AsymmetricCryptoUtil.GenerateKeyPair();

            var apiClient = new ApiClient(
                linkCode.ServerHttps,
                linkCode.ServerHost,
                linkCode.ServerPort,
                linkCode.ServerApiVersion);
            var request = new ServerAPIRequestsUnauthenticated.RegisterSecondDevice
            {
                LoginRequestIdentifier = linkCode.LoginIdentifier,
                PublicKeyPem           = newKeyPair.PublicPem,
                DeviceLabel            = "My Test Device",
                DeviceType             = "phone",
                DeviceSubtype          = "testdevice"
            };
            var response = request.GetResponse(apiClient);

            var apiClientAuthenticated = new ApiClient(
                linkCode.ServerHttps,
                linkCode.ServerHost,
                linkCode.ServerPort,
                linkCode.ServerApiVersion,
                response.ApiKey,
                newKeyPair.PrivatePem);

            var totpcode = new TimeBasedOtpGenerator(new Key(response.Secret), response.Digits, new SHA1HMACAlgorithm())
                           .GenerateOtp(DateTime.UtcNow);

            try
            {
                var confirmRequest = new ServerAPIRequests.ConfirmSecondDevice
                {
                    OtpCode = totpcode
                };
                confirmRequest.GetResponse(apiClientAuthenticated);
            }
            catch (RequestException)
            {
                MessageBox.Show(@"Unable to validate the device. Please try again.");
                return(false);
            }

            var serverInfo = apiClientAuthenticated.GetServerInfo(new GetServerInfoRequest());

            var newServerId = AppModel.ServerAccounts.Create(new AppModels.ServerAccount
            {
                ServerIdentifier = serverInfo.ServerIdentifier
            });

            var model = AccountModel.GetModel(newServerId);

            var newOtpAccountId = model.OtpAccounts.Create(new OtpAccount
            {
                Type      = response.Type,
                Label     = response.Label,
                Issuer    = response.Issuer,
                Secret    = response.Secret,
                Algorithm = response.Algorithm,
                Digits    = response.Digits,
                Counter   = response.Counter,
                Period    = response.Period
            });

            var cryptoKeyId = model.CryptoKeys.Create(new CryptoKey
            {
                OwnKey           = true,
                Trust            = true,
                PrivateKeyPem    = newKeyPair.PrivatePem,
                PublicKeyPem     = newKeyPair.PublicPem,
                PublicKeyPemHash = HashUtil.Sha256(newKeyPair.PublicPem)
            });

            var serverAccountSettingsId = model.ServerAccountSettings.Create(new ServerAccountSetting
            {
                Identifier       = serverInfo.ServerIdentifier,
                Label            = serverInfo.ServerLabel,
                HttpsEnabled     = linkCode.ServerHttps,
                Host             = linkCode.ServerHost,
                Port             = linkCode.ServerPort,
                ApiVersion       = linkCode.ServerApiVersion,
                UserIdentifier   = response.UserIdentifier,
                DeviceIdentifier = response.DeviceIdentifier,
                OtpAccountId     = newOtpAccountId,
                ApiKey           = response.ApiKey,
                EmailAddress     = linkCode.EmailAddress,
                ApiCryptoKeyId   = cryptoKeyId
            });

            var linkedDeviceRequest = new ServerAPIRequests.GetLinkedDevice();

            ServerAPIRequests.GetLinkedDevice.ResponseParams linkedDeviceResponse;
            linkedDeviceResponse = linkedDeviceRequest.GetResponse(apiClientAuthenticated);

            if (linkCode.InitiatingDevicePublicKeyPem != HashUtil.Sha256(linkedDeviceResponse.PublicKeyPem))
            {
                MessageBox.Show(@"Unable to verify device keys. You will need to do this manually from the desktop app.");
            }
            else
            {
                var linkedDeviceCryptoKeyId = model.CryptoKeys.Create(new CryptoKey
                {
                    Trust            = true,
                    PublicKeyPem     = linkedDeviceResponse.PublicKeyPem,
                    PublicKeyPemHash = HashUtil.Sha256(linkedDeviceResponse.PublicKeyPem)
                });
                model.ServerAccountSettings.Update(serverAccountSettingsId, new ServerAccountSetting
                {
                    LinkedDeviceCryptoKeyId = linkedDeviceCryptoKeyId
                });
            }

            _syncAccounts.Add(newServerId, new SyncAccounts(this, model));
            _syncAccounts[newServerId].Start();

            _mainForm.UpdateForm();

            return(true);
        }
Esempio n. 28
0
        private string GetResponseContent(string endpoint, object requestBody)
        {
            Logger.Verbose("Making request to " + endpoint + " endpoint...");

            var restClient  = new RestClient(_apiUrl);
            var restRequest = new RestRequest(endpoint, Method.POST)
            {
                RequestFormat = DataFormat.Json
            };
            var requestBodyString = JsonConvert.SerializeObject(requestBody);

            restRequest.AddParameter("application/json", requestBodyString, ParameterType.RequestBody);

            if (_isAuthorizedRequest)
            {
                if (string.IsNullOrEmpty(_clientId))
                {
                    throw new MissingFieldException("Client ID not provided for authenticated request.");
                }

                if (string.IsNullOrEmpty(_privateKeyPem))
                {
                    throw new MissingFieldException("Public key not provided");
                }

                var signature = AsymmetricCryptoUtil.CreateSignature(requestBodyString, _privateKeyPem);
                restRequest.AddHeader("Authorization", "token " + _clientId + ":" + signature);
            }

            var restResponse = restClient.Execute(restRequest);

            if (restResponse.StatusCode == 0)
            {
                throw new NetworkErrorException("Network error. Could not connect to server.");
            }

            if (restResponse.StatusCode != HttpStatusCode.OK)
            {
                ErrorResponse errorResponse;
                try
                {
                    errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(restResponse.Content);
                }
                catch (Exception)
                {
                    throw new RequestException("Unknown error whilst contacting server");
                }

                switch (restResponse.StatusCode)
                {
                case HttpStatusCode.BadRequest:
                    throw new BadRequestException(errorResponse.Error);

                case HttpStatusCode.Unauthorized:
                    throw new UnauthorizedException(errorResponse.Error);

                case HttpStatusCode.NotFound:
                    throw new NotFoundException(errorResponse.Error);

                case HttpStatusCode.Conflict:
                    throw new ConflictException(errorResponse.ErrorCode, errorResponse.Error);

                default:
                    throw new RequestException(errorResponse.ErrorCode, errorResponse.Error);
                }
            }

            Logger.Verbose("Received response: " + restResponse.Content);

            return(restResponse.Content);
        }
Esempio n. 29
0
        private async Task <string> GetResponseContent(string endpoint, string requestBody)
        {
            Logger.Verbose("Making request to " + endpoint + " endpoint...");

            var restClient  = new RestClient(ApiClient.ApiUrl);
            var restRequest = new RestRequest(endpoint, Method.POST)
            {
                RequestFormat = DataFormat.Json
            };

            restRequest.AddParameter("application/json", requestBody, ParameterType.RequestBody);

            if (IsAuthenticatedRequest)
            {
                if (string.IsNullOrEmpty(ApiClient.ApiKey))
                {
                    throw new MissingFieldException("API key not provided for authenticated request.");
                }

                if (string.IsNullOrEmpty(ApiClient.PrivateKeyPem))
                {
                    throw new MissingFieldException("Private key not provided");
                }

                var signature = AsymmetricCryptoUtil.CreateSignature(requestBody, ApiClient.PrivateKeyPem);
                restRequest.AddHeader("Authorization", "token " + ApiClient.ApiKey + ":" + signature);
            }

            IRestResponse restResponse = new RestResponse();

            if (InterruptHandleSet)
            {
                // Perform the request asynchronously, but block on the interrupt handle.
                var responseReceived = false;
                var asyncHandle      = restClient.ExecuteAsync(restRequest, response =>
                {
                    responseReceived = true;
                    restResponse     = response;
                    InterruptHandle.Set();
                });

                InterruptHandle.WaitOne();

                if (!responseReceived)
                {
                    asyncHandle.Abort();
                    throw new RequestException("Network error. Request was interrupted.");
                }
            }
            else
            {
                var cancellationTokenSource = new CancellationTokenSource();
                restResponse = await restClient.ExecuteTaskAsync(restRequest, cancellationTokenSource.Token);
            }

            if (restResponse.StatusCode == 0)
            {
                throw new RequestException("Network error. Could not connect to server.");
            }

            if (restResponse.StatusCode != HttpStatusCode.OK)
            {
                ErrorResponse errorResponse;
                try
                {
                    errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(restResponse.Content);
                }
                catch (Exception)
                {
                    throw new NetworkErrorException("Unknown error whilst contacting server");
                }

                switch (restResponse.StatusCode)
                {
                case HttpStatusCode.BadRequest:
                    throw new BadRequestException(errorResponse.Error);

                case HttpStatusCode.Unauthorized:
                    throw new UnauthorizedException(errorResponse.Error);

                case HttpStatusCode.NotFound:
                    throw new NotFoundException(errorResponse.Error);

                case HttpStatusCode.Conflict:
                    throw new NotFoundException(errorResponse.Error);

                default:
                    throw new RequestException(errorResponse.Error);
                }
            }

            Logger.Verbose("Received response: " + restResponse.Content);

            return(restResponse.Content);
        }