Ejemplo n.º 1
0
        public UserDTO AuthenticateUser(string username, string password)
        {
            User user = _users.Get(u => u.UserName.Equals(username) && u.Password.Equals(EncryptionHelpers.HashPassword(password, u.Salt))).FirstOrDefault();

            if (user != null && user.IsActive)
            {
                using (var transaction = _users.BeginTransaction())
                {
                    user          = _users.FindById(user.UserId);
                    user.Salt     = EncryptionHelpers.GenerateSalt();
                    user.Password = EncryptionHelpers.HashPassword(password, user.Salt);
                    _users.Save();
                    transaction.Commit();
                }
                return(Mapper.Map <User, UserDTO>(user));
            }
            else
            {
                throw new UnauthorizedAccessException("Wrong credentials.");
            }
        }
Ejemplo n.º 2
0
        public string Authorize(LoginUserViewModel model)
        {
            MUser  oUser    = oUserRepository.Get().Where(t => t.UserName == model.UserName && t.IsDeleted == 0 && t.UserPassword == model.UserPassword.Trim()).FirstOrDefault();
            string strToken = null;

            if (oUser != null)
            {
                strToken = EncryptionHelpers.GenerateString();
                var oDevice = oAccessTokenRepository.Get().Where(t => t.AccessTokenDevice == model.UserDevice).FirstOrDefault();
                if (oDevice == null)
                {
                    oAccessTokenRepository.Insert(new TAccessToken
                    {
                        AccessTokenDevice      = model.UserDevice,
                        AccessTokenKey         = strToken,
                        AccessTokenCreatedDate = DateTime.Now,
                        AccessTokenExpriedDate = DateTime.Now.AddMinutes(30),
                        UserId = oUser.UserId
                    });
                }
                else
                {
                    oDevice.AccessTokenKey         = strToken;
                    oDevice.AccessTokenUpdatedDate = DateTime.Now;
                    oDevice.AccessTokenExpriedDate = DateTime.Now.AddMinutes(30);
                    oAccessTokenRepository.Update(oDevice);
                }

                oAccessLogRepository.Insert(new TAccessLog
                {
                    AccessLogDevice      = model.UserDevice,
                    AccessLogKey         = strToken,
                    AccessLogUrl         = HTTPHelpers.HttpContext.Request.Path.ToString(),
                    AccessLogCreatedDate = DateTime.Now,
                    UserId = oUser.UserId
                });
            }
            return(strToken);
        }
        private void ReconstructFile(
            string destination,
            IEnumerable <Tuple <string, long> > localFileShardIDPathsAndIndices
            )
        {
            long currentShard = 0;

            using (FileStream outputFileStream = System.IO.File.Create(destination))
            {
                this.Info("Piecing file together");
                foreach (string fileShardPath in localFileShardIDPathsAndIndices.OrderBy(t => t.Item2).Select(t => t.Item1))
                {
                    this.Verbose($"Adding shard: {currentShard}");
                    // Load the bytes into memory
                    byte[] decryptedBytes = EncryptionHelpers.DecryptBytes(
                        System.IO.File.ReadAllBytes(fileShardPath),
                        _config.EncryptionKey,
                        _config.InitializationVector
                        );

                    // Load the string
                    FileShard deserializedFileShard =
                        JsonConvert.DeserializeObject <FileShard>(
                            Encoding.UTF8.GetString(decryptedBytes, 0, decryptedBytes.Length)
                            );

                    // Assert that the current shard equals the one we expect
                    if (deserializedFileShard.PieceNumber != currentShard)
                    {
                        throw new InvalidOperationException("The file shard IDs are out of order!");
                    }

                    outputFileStream.Write(deserializedFileShard.Payload, 0, deserializedFileShard.Payload.Length);
                    currentShard++;

                    System.IO.File.Delete(fileShardPath);
                }
            }
        }
Ejemplo n.º 4
0
        /// <inheritdoc />
        internal override async Task <List <EventMessage> > ProcessMessagesAsync(StreamEntry[] entries)
        {
            List <EventMessage> messages = await base.ProcessMessagesAsync(entries);

            foreach (EventMessage msg in messages)
            {
                try
                {
                    string?content = msg.Content as string;
                    if (content != null)
                    {
                        byte[] encrypted      = Convert.FromBase64String(content);
                        byte[] plaintextBytes = await EncryptionHelpers.DecryptDataAsync(encrypted, _encryptionKey).ConfigureAwait(false);

                        string plaintext = Encoding.UTF8.GetString(plaintextBytes);
                        msg.Content = plaintext;
                    }
                    else
                    {
                        msg.Content = string.Empty;
                    }
                }
                catch (Exception ex)
                {
                    Log.Logger.Error(
                        ex,
                        "Failed decrypting on Stream {Name} Consumer Group {Group} Consumer {Consumer} at {Offset}-{Sequence}: {Value}",
                        _streamName,
                        _consumerGroup,
                        _consumerName,
                        msg.Offset,
                        msg.SequenceNumber,
                        msg.Content?.ToString() ?? string.Empty);
                }
            }

            return(messages);
        }
        public async Task GetDecryptionStreamAsync_WithValidData_WritesDecryptedData()
        {
            byte[] key      = EncryptionHelpers.CreateEncryptionKey();
            byte[] original = new byte[128];
            new Random().NextBytes(original);
            byte[] encrypted = await EncryptionHelpers.EncryptDataAsync(original, key);

            byte[] result;
            using (MemoryStream ms = new MemoryStream(encrypted))
                using (MemoryStream output = new MemoryStream())
                {
                    using (Stream stream = await EncryptionHelpers.GetDecryptionStreamAsync(key, ms))
                    {
                        await stream.CopyToAsync(output);
                    }

                    result = output.ToArray();
                }

            Assert.NotNull(result);
            Assert.NotEmpty(result);
            Assert.Equal(original, result);
        }
Ejemplo n.º 6
0
        public void EditUser(UserDTO user, ICollection <GroupDTO> groups, ICollection <RoleDTO> roles)
        {
            if (user.UserName != null && user.Password != null)
            {
                User userToEdit = _users.FindById(user.UserId);
                if (user.Name != null)
                {
                    userToEdit.Name = user.Name;
                }
                if ((user.UserName != null || userToEdit.UserName == user.UserName) && CheckUser(user.UserName))
                {
                    userToEdit.UserName = user.UserName;
                }
                if (user.Password != null && user.Password != userToEdit.Password)
                {
                    var salt = EncryptionHelpers.GenerateSalt();
                    userToEdit.Salt     = salt;
                    userToEdit.Password = EncryptionHelpers.HashPassword(user.Password, salt);
                }
                if (user.IsActive != userToEdit.IsActive)
                {
                    userToEdit.IsActive = user.IsActive;
                }

                var convertRoles = new List <Role>();
                if (roles != null)
                {
                    var convert = Mapper.Map <IEnumerable <RoleDTO>, IEnumerable <Role> >(roles);
                    foreach (var item in convert)
                    {
                        if (_roles.FindById(item.RoleId) != null)
                        {
                            convertRoles.Add(_roles.FindById(item.RoleId));
                        }
                    }
                }

                if (roles.Any())
                {
                    userToEdit.Roles = convertRoles;
                }
                if (!roles.Any())
                {
                    userToEdit.Roles = null;
                }

                var convertGroups = new List <Group>();
                if (groups != null)
                {
                    var convert = Mapper.Map <IEnumerable <GroupDTO>, IEnumerable <Group> >(groups);
                    foreach (var item in convert)
                    {
                        if (_groups.FindById(item.GroupId) != null)
                        {
                            convertGroups.Add(_groups.FindById(item.GroupId));
                        }
                    }
                }

                if (groups.Any())
                {
                    userToEdit.Groups = convertGroups;
                }
                if (!groups.Any())
                {
                    userToEdit.Groups = null;
                }
                _users.Update(userToEdit);
                _context.SaveChanges();
            }
        }
Ejemplo n.º 7
0
 public Keyblock(ILog logger, EncryptionHelpers crypto, Settings settings) : base(logger)
 {
     _logger   = logger;
     _crypto   = crypto;
     _settings = settings;
 }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            var host = new HostBuilder()
                       .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment}.json", true, true)
                .AddEnvironmentVariables("VANGUARD_")
                .AddCommandLine(args)
                .Build();
            })
                       .ConfigureServices((hostingContext, services) =>
            {
                NodeOptions nodeOptions;
                if ((string)RegistryHelper.GetVanguardKey().GetValue("NodeInstalled") == "yes")
                {
                    nodeOptions = new NodeOptions
                    {
                        IsInstalled                     = true,
                        NodeName                        = RegistryHelper.GetVanguardKey().GetValue("NodeName") as string,
                        CoreConnectionHostname          = RegistryHelper.GetVanguardKey().GetValue("CoreConnectionHostname") as string,
                        CoreConnectionNoSsl             = (string)RegistryHelper.GetVanguardKey().GetValue("CoreConnectionNoSsl") == "yes",
                        CoreConnectionIgnoreSslWarnings = (string)RegistryHelper.GetVanguardKey().GetValue("CoreConnectionIgnoreSslWarnings") == "yes"
                    };
                }
                else
                {
                    nodeOptions = new NodeOptions();
                }
                services.AddSingleton(nodeOptions);

                services.AddSingleton <LocalCredentialsProvider>();
                services.AddSingleton <Authenticator>();
                services.AddTransient <NodeHttpClient>();
                services.AddSingleton <IHostedService, AuthService>();
                services.AddSingleton <IHostedService, NodeService>();
            })
                       .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            })
                       .UseConsoleLifetime()
                       .Build();

            var logger      = host.Services.GetService <ILoggerFactory>().CreateLogger("Main");
            var hostOptions = host.Services.GetService <NodeOptions>();

            var app = new CommandLineApplication {
                Name = "Vanguard Server Manager Node"
            };

            app.HelpOption("-?|-h|--help", true);

            app.Command("install", command =>
            {
                var nodeNameOption     = command.Option <string>("-n|--name", "Name of the server manager node", CommandOptionType.SingleValue);
                var coreHostnameOption = command.Option <string>("-a|--address", "Hostname or IP address of the server manager core server", CommandOptionType.SingleValue);
                var certificateFile    = command.Option <string>("-c|--certificate", "Provide a certificate instead of generating a self-signed one", CommandOptionType.SingleValue);
                var certificateKeyFile = command.Option <string>("-k|--key-file", "Provide a certificate key file instead of prompting for password for the provided certificate file", CommandOptionType.SingleValue);
                var useHttp            = command.Option <bool>("--no-ssl", "Don't use HTTPS for core communication", CommandOptionType.NoValue);
                var useInsecure        = command.Option <bool>("--insecure", "Ignore SSL warnings and errors", CommandOptionType.NoValue);

                command.OnExecute(async() =>
                {
                    try
                    {
                        if (hostOptions.IsInstalled)
                        {
                            logger.LogInformation("The service has already been installed");
                            return(0);
                        }

                        var nodeName     = nodeNameOption.HasValue() ? nodeNameOption.ParsedValue : Prompt.GetString("Name of the server manager node (Must be unique):");
                        var coreHostname = coreHostnameOption.HasValue() ? coreHostnameOption.ParsedValue : Prompt.GetString("Hostname or IP address of the server manager core server:");
                        var coreUsername = Prompt.GetString("Username for the registration:");
                        var corePassword = Prompt.GetPassword("Password for the registration:");

                        X509Certificate2 certificate;
                        if (certificateFile.HasValue())
                        {
                            certificate = EncryptionHelpers.LoadServerNodeCertificate(certificateFile.ParsedValue, certificateKeyFile.ParsedValue);
                        }
                        else
                        {
                            // TODO: Check for generated certificate and load it

                            var password        = Prompt.GetPassword("Provide the certificate password:"******"Confirm the certificate password:"******"Passwords don't match");
                            }

                            certificate = EncryptionHelpers.GenerateServerNodeCertificate(nodeName, password);
                        }

                        var nodeOptions = new NodeOptions
                        {
                            CoreConnectionHostname          = coreHostname,
                            CoreConnectionNoSsl             = useHttp.HasValue(),
                            CoreConnectionIgnoreSslWarnings = useInsecure.HasValue()
                        };
                        var authenticator = new Authenticator(nodeOptions);
                        try
                        {
                            await authenticator.AuthenticateAsync(coreUsername, corePassword);
                        }
                        catch (Exception ex)
                        {
                            logger.LogError("Failed to authenticate for installation: {0}", ex);
                            return(1);
                        }

                        using (var client = new NodeHttpClient(authenticator, nodeOptions))
                        {
                            var registrationPayload = JsonConvert.SerializeObject(new ServerNodeViewModel
                            {
                                Name      = nodeName,
                                PublicKey = certificate.GetPublicKeyString()
                            }, Formatting.None, new JsonSerializerSettings {
                                ContractResolver = new CamelCasePropertyNamesContractResolver()
                            });
                            logger.LogInformation("Starting node registration");
                            logger.LogDebug("Attempting to register the node");
                            logger.LogTrace(registrationPayload);
                            var registrationResponse = await client.PostAsync($"{nodeOptions.ApiRoot}/api/node", new StringContent(registrationPayload, Encoding.Default, "application/json"));
                            if (!registrationResponse.IsSuccessStatusCode)
                            {
                                logger.LogError("Failed to register the node: [{0}] {1}", registrationResponse.StatusCode, await registrationResponse.Content.ReadAsStringAsync());
                                return(1);
                            }

                            var credentials = JsonConvert.DeserializeObject <UsernamePasswordCredentialsViewModel>(await registrationResponse.Content.ReadAsStringAsync());
                            var localCredentialsProvider = host.Services.GetService <LocalCredentialsProvider>();
                            try
                            {
                                await localCredentialsProvider.SetCredentialsAsync("CoreConnectionCredentials", credentials);
                            }
                            catch (CredentialProviderException ex)
                            {
                                // TODO: Implement recovery action via option flag to generate a new password
                                logger.LogError("Failed to store retrieved credentials: {0}", ex);
                                return(1);
                            }

                            RegistryHelper.GetVanguardKey().SetValue("NodeInstalled", "yes");
                            RegistryHelper.GetVanguardKey().SetValue("NodeName", nodeName);
                            RegistryHelper.GetVanguardKey().SetValue("CoreConnectionHostname", coreHostname);
                            RegistryHelper.GetVanguardKey().SetValue("CoreConnectionNoSsl", useHttp.HasValue() ? "yes" : "no");
                            RegistryHelper.GetVanguardKey().SetValue("CoreConnectionIgnoreSslWarnings", useInsecure.HasValue() ? "yes" : "no");
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError("Install failed due to an unexpected exception: {0}", ex);
                        throw;
                    }

                    return(0);
                });
            });

            app.Command("start", command =>
            {
                var foregroundSwitch = command.Option("-f|--foreground", "Run the service in foreground mode", CommandOptionType.NoValue);

                command.OnExecute(async() =>
                {
                    using (host)
                    {
                        var nodeOptions = host.Services.GetService <NodeOptions>();
                        if (!nodeOptions.IsInstalled)
                        {
                            logger.LogInformation("The service has not been installed yet");
                            return(1);
                        }

                        try
                        {
                            if (foregroundSwitch.HasValue())
                            {
                                // TODO: Remove when child process kill has been fixed. See https://github.com/dotnet/cli/issues/7426
                                var cancellationTokenSource          = new CancellationTokenSource();
                                AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) =>
                                {
                                    cancellationTokenSource.Cancel();
                                };
                                Console.CancelKeyPress += (sender, e) =>
                                {
                                    e.Cancel = true;
                                    cancellationTokenSource.Cancel();
                                };

                                await host.StartAsync(cancellationTokenSource.Token);
                                await host.WaitForShutdownAsync(cancellationTokenSource.Token);
                                //await host.StartAsync();
                                //await host.WaitForShutdownAsync();
                            }
                            else
                            {
                                host.RunAsService();
                            }
                        }
                        catch (TaskCanceledException)
                        {
                            return(0);
                        }
                        catch (Exception ex)
                        {
                            logger.LogError("Start failed due to an unexpected exception: {0}", ex);
                            return(1);
                        }

                        return(0);
                    }
                });
            });

            if (args.Length == 0)
            {
                app.ShowHint();
            }
            else
            {
                app.Execute(args);
            }
        }
 public async Task DecryptDataAsync_WithEmptyData_Throws()
 {
     byte[] key = EncryptionHelpers.CreateEncryptionKey();
     await Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() => await EncryptionHelpers.DecryptDataAsync(Array.Empty <byte>(), key));
 }
 public async Task EncryptDataAsync_WithEmptyEncryptionKey_Throws()
 {
     byte[] data = EncryptionHelpers.CreateEncryptionKey();
     await Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() => await EncryptionHelpers.EncryptDataAsync(data, Array.Empty <byte>()));
 }
 public async Task EncryptDataAsync_WithNullEncryptionKey_Throws()
 {
     byte[] data = EncryptionHelpers.CreateEncryptionKey();
     await Assert.ThrowsAsync <ArgumentNullException>(async() => await EncryptionHelpers.EncryptDataAsync(data, null));
 }
 public void CreateEncryptionKey_WithInvalidSpecifiedKeySize_Throws(int keySize)
 {
     Assert.Throws <CryptographicException>(() => EncryptionHelpers.CreateEncryptionKey(keySize));
 }
 public async Task GetDecryptionStreamAsync_WithNonReadableStream_Throws()
 {
     byte[] key = EncryptionHelpers.CreateEncryptionKey();
     await Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() => await EncryptionHelpers.GetDecryptionStreamAsync(key, new NonReadableStream()));
 }
 public async Task GetDecryptionStreamAsync_WithEmptyEncryptionKey_Throws()
 {
     using (MemoryStream ms = new MemoryStream())
     {
         await Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() => await EncryptionHelpers.GetDecryptionStreamAsync(Array.Empty <byte>(), ms));
     }
 }
 public async Task GetDecryptionStreamAsync_WithNullStream_Throws()
 {
     byte[] key = EncryptionHelpers.CreateEncryptionKey();
     await Assert.ThrowsAsync <ArgumentNullException>(async() => await EncryptionHelpers.GetDecryptionStreamAsync(key, null));
 }
Ejemplo n.º 16
0
        /// <summary>
        ///     Generate a new Minisign key pair.
        /// </summary>
        /// <param name="password">The password to protect the secret key.</param>
        /// <param name="writeOutputFiles">If false, no files will be written.</param>
        /// <param name="outputFolder">The folder to write the files (optional).</param>
        /// <param name="keyPairFileName">The name of the files to write (optional).</param>
        /// <returns>A MinisignKeyPair object.</returns>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="OverflowException"></exception>
        /// <exception cref="DirectoryNotFoundException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="IOException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        /// <exception cref="PathTooLongException"></exception>
        /// <exception cref="SecurityException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static MinisignKeyPair GenerateKeyPair(string password, bool writeOutputFiles = false,
                                                      string outputFolder = "", string keyPairFileName = "minisign")
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password), "password can not be null");
            }

            if (writeOutputFiles)
            {
                //validate the outputFolder
                if (string.IsNullOrEmpty(outputFolder) || !Directory.Exists(outputFolder))
                {
                    throw new DirectoryNotFoundException("outputFolder must exist");
                }

                if (outputFolder.IndexOfAny(Path.GetInvalidPathChars()) > -1)
                {
                    throw new ArgumentException("The given path to the output folder contains invalid characters!");
                }

                //validate the keyPairFileName
                if (string.IsNullOrEmpty(keyPairFileName))
                {
                    throw new ArgumentNullException(nameof(keyPairFileName), "keyPairFileName can not be empty");
                }
            }

            var minisignKeyPair    = new MinisignKeyPair();
            var minisignPrivateKey = new MinisignPrivateKey();
            var keyPair            = PublicKeyAuth.GenerateKeyPair();
            var keyId   = SodiumCore.GetRandomBytes(KeyNumBytes);
            var kdfSalt = SodiumCore.GetRandomBytes(32);

            minisignPrivateKey.PublicKey          = keyPair.PublicKey;
            minisignPrivateKey.KdfSalt            = kdfSalt;
            minisignPrivateKey.SignatureAlgorithm = Encoding.UTF8.GetBytes(Sigalg);
            minisignPrivateKey.ChecksumAlgorithm  = Encoding.UTF8.GetBytes(Chkalg);
            minisignPrivateKey.KdfAlgorithm       = Encoding.UTF8.GetBytes(Kdfalg);
            minisignPrivateKey.KdfMemLimit        = 1073741824;    //currently unused
            minisignPrivateKey.KdfOpsLimit        = 33554432;      //currently unused

            var checksum =
                GenericHash.Hash(
                    ArrayHelpers.ConcatArrays(minisignPrivateKey.SignatureAlgorithm, keyId, keyPair.PrivateKey), null,
                    32);

            minisignPrivateKey.KeyId     = keyId;
            minisignPrivateKey.SecretKey = keyPair.PrivateKey;
            minisignPrivateKey.Checksum  = checksum;

            var dataToProtect = ArrayHelpers.ConcatArrays(keyId, keyPair.PrivateKey, checksum);
            var encryptionKey = PasswordHash.ScryptHashBinary(Encoding.UTF8.GetBytes(password),
                                                              minisignPrivateKey.KdfSalt,
                                                              PasswordHash.Strength.Sensitive,
                                                              104);

            var encryptedKeyData = EncryptionHelpers.Xor(dataToProtect, encryptionKey);
            // set up the public key
            var minisignPublicKey = new MinisignPublicKey
            {
                KeyId              = keyId,
                PublicKey          = keyPair.PublicKey,
                SignatureAlgorithm = Encoding.UTF8.GetBytes(Sigalg)
            };

            keyPair.Dispose();
            if (writeOutputFiles)
            {
                var privateKeyOutputFileName = Path.Combine(outputFolder, keyPairFileName + PrivateKeyFileSuffix);
                var publicKeyOutputFileName  = Path.Combine(outputFolder, keyPairFileName + PublicKeyFileSuffix);

                var binaryPublicKey = ArrayHelpers.ConcatArrays(
                    minisignPublicKey.SignatureAlgorithm,
                    minisignPublicKey.KeyId,
                    minisignPublicKey.PublicKey
                    );

                var publicFileContent = new[]
                {
                    CommentPrefix + "minisign public key " +
                    Utilities.BinaryToHex(minisignPublicKey.KeyId, Utilities.HexFormat.None, Utilities.HexCase.Upper),
                    Convert.ToBase64String(binaryPublicKey)
                };

                var binaryPrivateKey = ArrayHelpers.ConcatArrays(
                    minisignPrivateKey.SignatureAlgorithm,
                    minisignPrivateKey.KdfAlgorithm,
                    minisignPrivateKey.ChecksumAlgorithm,
                    minisignPrivateKey.KdfSalt,
                    BitConverter.GetBytes(minisignPrivateKey.KdfOpsLimit),
                    BitConverter.GetBytes(minisignPrivateKey.KdfMemLimit),
                    encryptedKeyData
                    );

                var privateFileContent = new[]
                {
                    CommentPrefix + PrivateKeyDefaultComment,
                    Convert.ToBase64String(binaryPrivateKey)
                };
                // files will be overwritten!
                File.WriteAllLines(publicKeyOutputFileName, publicFileContent);
                File.WriteAllLines(privateKeyOutputFileName, privateFileContent);

                minisignKeyPair.MinisignPublicKeyFilePath  = publicKeyOutputFileName;
                minisignKeyPair.MinisignPrivateKeyFilePath = privateKeyOutputFileName;
            }

            minisignKeyPair.MinisignPublicKey  = minisignPublicKey;
            minisignKeyPair.MinisignPrivateKey = minisignPrivateKey;
            return(minisignKeyPair);
        }
Ejemplo n.º 17
0
        /// <summary>
        ///     Load a public key into a MinisignPublicKey object.
        /// </summary>
        /// <param name="privateKey">A valid private key.</param>
        /// <param name="password">The password to decrypt the private key.</param>
        /// <returns>A MinisignPrivateKey object.</returns>
        /// <exception cref="OverflowException"></exception>
        /// <exception cref="CorruptPrivateKeyException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        public static MinisignPrivateKey LoadPrivateKey(byte[] privateKey, byte[] password)
        {
            if (privateKey == null)
            {
                throw new ArgumentException("missing privateKey input", nameof(privateKey));
            }

            if (password == null)
            {
                throw new ArgumentException("missing password input", nameof(password));
            }

            var minisignPrivateKey = new MinisignPrivateKey
            {
                SignatureAlgorithm = ArrayHelpers.SubArray(privateKey, 0, 2),
                KdfAlgorithm       = ArrayHelpers.SubArray(privateKey, 2, 2),
                ChecksumAlgorithm  = ArrayHelpers.SubArray(privateKey, 4, 2),
                KdfSalt            = ArrayHelpers.SubArray(privateKey, 6, 32),
                KdfOpsLimit        = BitConverter.ToInt64(ArrayHelpers.SubArray(privateKey, 38, 8), 0),         //currently unused
                KdfMemLimit        = BitConverter.ToInt64(ArrayHelpers.SubArray(privateKey, 46, 8), 0)          //currently unused
            };

            if (!minisignPrivateKey.SignatureAlgorithm.SequenceEqual(Encoding.UTF8.GetBytes(Sigalg)))
            {
                throw new CorruptPrivateKeyException("bad SignatureAlgorithm");
            }

            if (!minisignPrivateKey.ChecksumAlgorithm.SequenceEqual(Encoding.UTF8.GetBytes(Chkalg)))
            {
                throw new CorruptPrivateKeyException("bad ChecksumAlgorithm");
            }

            if (!minisignPrivateKey.KdfAlgorithm.SequenceEqual(Encoding.UTF8.GetBytes(Kdfalg)))
            {
                throw new CorruptPrivateKeyException("bad KdfAlgorithm");
            }

            if (minisignPrivateKey.KdfSalt.Length != KeySaltBytes)
            {
                throw new CorruptPrivateKeyException("bad KdfSalt length");
            }

            var encryptedKeyData = ArrayHelpers.SubArray(privateKey, 54, 104);

            var decryptionKey = PasswordHash.ScryptHashBinary(password, minisignPrivateKey.KdfSalt,
                                                              PasswordHash.Strength.Sensitive,
                                                              104);

            var decryptedKeyData = EncryptionHelpers.Xor(encryptedKeyData, decryptionKey);

            minisignPrivateKey.KeyId     = ArrayHelpers.SubArray(decryptedKeyData, 0, 8);
            minisignPrivateKey.SecretKey = ArrayHelpers.SubArray(decryptedKeyData, 8, 64);
            minisignPrivateKey.Checksum  = ArrayHelpers.SubArray(decryptedKeyData, 72, 32);

            if (minisignPrivateKey.KeyId.Length != KeyNumBytes)
            {
                throw new CorruptPrivateKeyException("bad KeyId length");
            }

            var calculatedChecksum =
                GenericHash.Hash(
                    ArrayHelpers.ConcatArrays(minisignPrivateKey.SignatureAlgorithm, minisignPrivateKey.KeyId,
                                              minisignPrivateKey.SecretKey), null, 32);

            if (!ArrayHelpers.ConstantTimeEquals(minisignPrivateKey.Checksum, calculatedChecksum))
            {
                throw new CorruptPrivateKeyException("bad private key checksum");
            }
            // extract the public key from the private key
            minisignPrivateKey.PublicKey =
                PublicKeyAuth.ExtractEd25519PublicKeyFromEd25519SecretKey(minisignPrivateKey.SecretKey);

            return(minisignPrivateKey);
        }
Ejemplo n.º 18
0
 public NewCamdApi(ILog logger, IThreadHelper threadHelper, Settings settings, EncryptionHelpers crypto, NewCamdCommunication communication, Keyblock keyblock)
 {
     _logger        = logger;
     _threadHelper  = threadHelper;
     _settings      = settings;
     _crypto        = crypto;
     _communication = communication;
     _keyblock      = keyblock;
     _communication.MessageReceived += (sender, message) => ReceiveMessage(message);
     _communication.Closed          += (sender, message) => Closed?.Invoke(this, null);
 }
        /// <inheritdoc />
        protected override async Task <QueueMessage> GetQueueMessageAsync(ReadOnlyMemory <byte> body, IBasicProperties properties, bool redelivered, ulong messageId)
        {
            byte[] decrypted = await EncryptionHelpers.DecryptDataAsync(body, _encryptionKey);

            return(new QueueMessage(properties, decrypted, redelivered, messageId));
        }
 public async Task DecryptDataAsync_WithNullData_Throws()
 {
     byte[] key = EncryptionHelpers.CreateEncryptionKey();
     await Assert.ThrowsAsync <ArgumentNullException>(async() => await EncryptionHelpers.DecryptDataAsync(null, key));
 }