private bool DecryptDataKey(string keyName, byte[] encryptedDataKey, IList <KeyValue> encKeyMeta, ICryptoKeyReader keyReader) { // Read the private key info using callback EncryptionKeyInfo keyInfo = keyReader.GetPrivateKey(keyName, encKeyMeta.ToDictionary(x => x.Key, x => x.Value)); // Convert key from byte to PivateKey // Decrypt data key to decrypt messages byte[] dataKeyValue; string keyDigest; try { // Decrypt data key using private key dataKeyValue = CryptoHelper.Decrypt(encryptedDataKey, keyInfo.Key); keyDigest = Convert.ToBase64String(_hash.ComputeHash(encryptedDataKey)); } catch (Exception e) { _log.Error($"{_logCtx} Failed to decrypt data key {keyName} to decrypt messages {e.Message}"); return(false); } _dataKey = dataKeyValue; _dataKeyCache.Put(keyDigest, _dataKey); return(true); }
public async Task GetRecommendationsWithEncryptedCredentials() { var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var portNumber = 4000; var aes = Aes.Create(); aes.GenerateKey(); aes.GenerateIV(); using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ResolveCredentials, aes); InMemoryInteractiveService interactiveService = new InMemoryInteractiveService(); var keyInfo = new EncryptionKeyInfo { Version = EncryptionKeyInfo.VERSION_1_0, Key = Convert.ToBase64String(aes.Key), IV = Convert.ToBase64String(aes.IV) }; var keyInfoStdin = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(keyInfo))); await interactiveService.StdInWriter.WriteAsync(keyInfoStdin); await interactiveService.StdInWriter.FlushAsync(); var serverCommand = new ServerModeCommand(interactiveService, portNumber, null, false); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var restClient = new RestAPIClient($"http://localhost:{portNumber}/", httpClient); await WaitTillServerModeReady(restClient); var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = _awsRegion, ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; Assert.NotNull(sessionId); var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId); Assert.NotEmpty(getRecommendationOutput.Recommendations); Assert.Equal("AspNetAppElasticBeanstalkLinux", getRecommendationOutput.Recommendations.FirstOrDefault().RecipeId); var listDeployStdOut = interactiveService.StdOutReader.ReadAllLines(); Assert.Contains("Waiting on symmetric key from stdin", listDeployStdOut); Assert.Contains("Encryption provider enabled", listDeployStdOut); } finally { cancelSource.Cancel(); } }
public EncryptionKeyInfo GetPrivateKey(string keyName, IDictionary <string, string> metadata) { EncryptionKeyInfo keyInfo = new EncryptionKeyInfo(); string privateKey = _privateKeys.GetOrDefault(keyName, _defaultPrivateKey); keyInfo.Key = LoadKey(privateKey); return(keyInfo); }
public async Task Start(CancellationToken cancellationToken) { var deployToolRoot = "dotnet aws"; if (!string.IsNullOrEmpty(_deployToolPath)) { if (!PathUtilities.IsDeployToolPathValid(_deployToolPath)) { throw new InvalidAssemblyReferenceException("The specified assembly location is invalid."); } deployToolRoot = _deployToolPath; } var currentProcessId = Process.GetCurrentProcess().Id; for (var port = _startPort; port <= _endPort; port++) { _aes = Aes.Create(); _aes.GenerateKey(); var keyInfo = new EncryptionKeyInfo( EncryptionKeyInfo.VERSION_1_0, Convert.ToBase64String(_aes.Key)); var keyInfoStdin = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(keyInfo))); var command = $"{deployToolRoot} server-mode --port {port} --parent-pid {currentProcessId}"; var startServerTask = _commandLineWrapper.Run(command, keyInfoStdin); _baseUrl = $"http://localhost:{port}"; var isServerAvailableTask = IsServerAvailable(cancellationToken); if (isServerAvailableTask == await Task.WhenAny(startServerTask, isServerAvailableTask).ConfigureAwait(false)) { // The server timed out, this isn't a transient error, therefore, we throw if (!isServerAvailableTask.Result) { throw new InternalServerModeException($"\"{command}\" failed for unknown reason."); } // Server has started, it is safe to return return; } // For -100 errors, we want to check all the ports in the configured port range // If the error code other than -100, this is an unexpected exit code. if (startServerTask.Result != TCP_PORT_ERROR) { throw new InternalServerModeException($"\"{command}\" failed for unknown reason."); } } throw new PortUnavailableException($"Free port unavailable in {_startPort}-{_endPort} range."); }
private void AddPublicKeyCipher(string keyName, ICryptoKeyReader keyReader) { if (string.ReferenceEquals(keyName, null) || keyReader == null) { throw new PulsarClientException.CryptoException("Keyname or KeyReader is null"); } // Read the public key and its info using callback var keyInfo = keyReader.GetPublicKey(keyName, null); var encryptedKey = CryptoHelper.Encrypt(_dataKey, keyInfo.Key); var eki = new EncryptionKeyInfo(encryptedKey, keyInfo.Metadata); _encryptedDataKeyMap[keyName] = eki; }
public EncryptionKeyInfo GetPrivateKey(string keyName, IDictionary <string, string> metadata) { var keyInfo = new EncryptionKeyInfo(); try { keyInfo.Key = (byte[])(object)File.ReadAllBytes(Path.GetFullPath(_privateKeyFile)); keyInfo.Metadata = metadata; } catch (IOException e) { Console.WriteLine($"ERROR: Failed to read public key from file {_publicKeyFile}"); } return(keyInfo); }
public async Task AuthEncryptionWithInvalidVersion() { InMemoryInteractiveService interactiveService = new InMemoryInteractiveService(); var portNumber = 4010; var aes = Aes.Create(); aes.GenerateKey(); aes.GenerateIV(); var keyInfo = new EncryptionKeyInfo { Version = "not-valid", Key = Convert.ToBase64String(aes.Key), IV = Convert.ToBase64String(aes.IV) }; var keyInfoStdin = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(keyInfo))); await interactiveService.StdInWriter.WriteAsync(keyInfoStdin); await interactiveService.StdInWriter.FlushAsync(); var serverCommand = new ServerModeCommand(interactiveService, portNumber, null, false); var cancelSource = new CancellationTokenSource(); Exception actualException = null; try { await serverCommand.ExecuteAsync(cancelSource.Token); } catch (InvalidEncryptionKeyInfoException e) { actualException = e; } finally { cancelSource.Cancel(); } Assert.NotNull(actualException); Assert.Equal("Unsupported symmetric key not-valid", actualException.Message); }
private IEncryptionProvider CreateEncryptionProvider() { IEncryptionProvider encryptionProvider; if (_noEncryptionKeyInfo) { encryptionProvider = new NoEncryptionProvider(); } else { _interactiveService.WriteLine("Waiting on symmetric key from stdin"); var input = _interactiveService.ReadLine(); var keyInfo = EncryptionKeyInfo.ParseStdInKeyInfo(input); switch (keyInfo.Version) { case EncryptionKeyInfo.VERSION_1_0: var aes = Aes.Create(); if (keyInfo.Key != null) { aes.Key = Convert.FromBase64String(keyInfo.Key); } encryptionProvider = new AesEncryptionProvider(aes); break; case null: throw new InvalidEncryptionKeyInfoException("Missing required \"Version\" property in the symmetric key"); default: throw new InvalidEncryptionKeyInfoException($"Unsupported symmetric key {keyInfo.Version}"); } _interactiveService.WriteLine("Encryption provider enabled"); } return(encryptionProvider); }