public boolean initializeMasterKeyFile(File masterKeyFile, String masterKey) {
    LOG.debug("Persisting master key into {}", masterKeyFile.getAbsolutePath());

    String encryptedMasterKey = null;
    if (masterKey != null) {
      try {
        encryptedMasterKey = encryptionService.encrypt(masterKey, MASTER_PASSPHRASE);
      } catch (Exception e) {
        LOG.error(String.format("Failed to encrypt master key, no changes have been made: %s", e.getLocalizedMessage()), e);
        return false;
      }
    }

    if (masterKeyFile.exists()) {
      if ((masterKeyFile.length() == 0) || isMasterKeyFile(masterKeyFile)) {
        LOG.info(String.format("Master key file exists at %s, resetting.", masterKeyFile.getAbsolutePath()));
        try (FileOutputStream fos = new FileOutputStream(masterKeyFile); FileChannel fileChannel = fos.getChannel();) {
          fileChannel.truncate(0);
        } catch (FileNotFoundException e) {
          LOG.error(String.format("Failed to open key file at %s: %s", masterKeyFile.getAbsolutePath(), e.getLocalizedMessage()), e);
        } catch (IOException e) {
          LOG.error(String.format("Failed to reset key file at %s: %s", masterKeyFile.getAbsolutePath(), e.getLocalizedMessage()), e);
        }
      } else {
        LOG.info(String.format("File exists at %s, but may not be a master key file. " +
            "It must be manually removed before this file location can be used", masterKeyFile.getAbsolutePath()));
        return false;
      }
    }

    if (encryptedMasterKey != null) {
      try {
        ArrayList<String> lines = new ArrayList<>();
        lines.add(MASTER_PERSISTENCE_TAG_PREFIX + TimeStamp.getCurrentTime().toDateString());
        lines.add(encryptedMasterKey);
        FileUtils.writeLines(masterKeyFile, "UTF8", lines);

        // restrict os permissions to only the user running this process
        protectAccess(masterKeyFile);
      } catch (IOException e) {
        LOG.error(String.format("Failed to persist master key to %s: %s ", masterKeyFile.getAbsolutePath(), e.getLocalizedMessage()), e);
        return false;
      }
    }

    return true;
  }
Initializes the master key file.
<p/>
If the specified file already exists, it it tested to see if it is a master key file. If so, it
will be truncated and the new master key will be stored in the new file. If the file appears
to not be a master key file,no changes will be made. The user must manually remove the file if
deemed appropriate.

@param masterKeyFile the file to write the master key to
@param masterKey     the master key
@return true if the master key was written to the specified file; otherwise false
ambari-server/src/main/java/org/apache/ambari/server/security/encryption/MasterKeyServiceImpl.java