private boolean savePassword(String password, IPreferencesContainer container) {
   byte[] data = winencrypt(password.getBytes());
   if (data == null) { // this is bad. Something wrong with OS or JNI.
     StorageException e =
         new StorageException(
             StorageException.ENCRYPTION_ERROR, WinCryptoMessages.encryptPasswordFailed);
     AuthPlugin.getDefault().logError(WinCryptoMessages.encryptPasswordFailed, e);
     return false;
   }
   String encodedEncryptyedPassword = Base64.encode(data);
   ISecurePreferences node = container.getPreferences().node(WIN_PROVIDER_NODE);
   try {
     node.put(
         PASSWORD_KEY,
         encodedEncryptyedPassword,
         false); // note we don't recursively try to encrypt
   } catch (StorageException e) { // should never happen in this scenario
     AuthPlugin.getDefault().logError(SecAuthMessages.errorOnSave, e);
     return false;
   }
   try {
     node.flush(); // save right away
   } catch (IOException e) {
     AuthPlugin.getDefault().logError(SecAuthMessages.errorOnSave, e);
     return false;
   }
   return true;
 }
    public synchronized Authorization authorize(URI uri) {
      String host = getHost(uri);
      if (host != null) {
        Authorization cachedAuthorization = authorizations.get(host);
        if (cachedAuthorization == Authorization.UNAUTHORIZEABLE) {
          return cachedAuthorization;
        }

        if (securePreferences != null) {
          try {
            ISecurePreferences node = securePreferences.node(host);
            String user = node.get("user", "");
            String password = node.get("password", "");

            Authorization authorization = new Authorization(user, password);
            if (authorization.isAuthorized()) {
              authorizations.put(host, authorization);
              return authorization;
            }
          } catch (StorageException ex) {
            SetupCorePlugin.INSTANCE.log(ex);
          }
        }

        if (cachedAuthorization != null) {
          return cachedAuthorization;
        }
      }

      return Authorization.UNAUTHORIZED;
    }
  /**
   * An internal method only available for the {@link PlatformCredentialsProvider} to clear all
   * secure preferences nodes. This method is called e.g. when the master password is to be changed
   * or disabled.
   */
  public void clear() {

    /* Clear In-Memory Store */
    fInMemoryStore.clear();

    /* Clear unprotected links cache */
    fUnprotectedLinksCache.clear();

    /* Clear cached info */
    InternalExchangeUtils.passwordProvidersReset();

    /* Remove all Nodes */
    ISecurePreferences secureRoot = getSecurePreferences();

    /* Check if Bundle is Stopped */
    if (secureRoot == null) return;

    String[] childrenNames = secureRoot.childrenNames();
    for (String child : childrenNames) {
      secureRoot.node(child).removeNode();
    }

    /* Flush to Disk */
    try {
      secureRoot.flush();
    } catch (IOException e) {
      Activator.getDefault().logError(e.getMessage(), e);
    }
  }
 /**
  * Answer secured preferences which can be used for storing sensitive information of this tab
  *
  * @return default instance of secure preferences for this tab, <code>null</code> if application
  *     was unable to create secure preferences using default location
  */
 private ISecurePreferences getPreferences(String sectionName) {
   ISecurePreferences preferences = SecurePreferencesFactory.getDefault();
   if (preferences == null) {
     return null;
   }
   return preferences.node(IPDEUIConstants.PLUGIN_ID).node(sectionName);
 }
 private String loadSecurePassword(String login) {
   ISecurePreferences node = getPasswordNode(login);
   if (node != null)
     try {
       return node.get("password", null);
     } catch (StorageException e) {
     }
   return null;
 }
 private void saveSecurePassword(String login, String password) {
   ISecurePreferences node = getPasswordNode(login);
   if (node != null) {
     try {
       node.put("password", password, true); // $NON-NLS-1$
     } catch (StorageException ex) {
       /* ignored on purpose */
     }
   }
 }
 private byte[] getEncryptedPassword(IPreferencesContainer container) {
   ISecurePreferences node = container.getPreferences().node(WIN_PROVIDER_NODE);
   String passwordHint;
   try {
     passwordHint = node.get(PASSWORD_KEY, null);
   } catch (StorageException e) { // should never happen in this scenario
     AuthPlugin.getDefault().logError(WinCryptoMessages.decryptPasswordFailed, e);
     return null;
   }
   if (passwordHint == null) return null;
   return Base64.decode(passwordHint);
 }
 private String getString(ISecurePreferences settings, String key) {
   try {
     return settings.get(key, ""); // $NON-NLS-1$
   } catch (StorageException e) {
     return ""; //$NON-NLS-1$
   }
 }
 private boolean getBoolean(ISecurePreferences settings, String key) {
   try {
     return settings.getBoolean(key, false);
   } catch (StorageException e) {
     return false;
   }
 }
  private ISecurePreferences getPasswordNode(String login) {
    if (login == null) return null;

    ISecurePreferences preferences = SecurePreferencesFactory.getDefault();
    if (preferences == null) return null;

    String host = Strings.trimToNull(preferenceHelper.getForgeURI());
    if (host == null) return null;

    StringBuilder bld = new StringBuilder();
    bld.append("/Puppetforge Credentials/"); // $NON-NLS-1$
    bld.append(login);
    bld.append('/');
    Checksums.appendSHA1(bld, host);
    return preferences.node(bld.toString());
  }
    public synchronized Authorization reauthorize(URI uri, Authorization authorization) {
      // Double check that another thread hasn't already prompted and updated the secure store or
      // has not already permanently failed to authorize.
      Authorization currentAuthorization = authorize(uri);
      if (!currentAuthorization.equals(authorization)
          || currentAuthorization == Authorization.UNAUTHORIZEABLE) {
        return currentAuthorization;
      }

      if (uiServices != null) {
        String host = getHost(uri);
        if (host != null) {
          AuthenticationInfo authenticationInfo = uiServices.getUsernamePassword(uri.toString());
          String user = authenticationInfo.getUserName();
          String password = authenticationInfo.getPassword();
          Authorization reauthorization = new Authorization(user, password);
          if (reauthorization.isAuthorized()) {
            if (authenticationInfo.saveResult() && securePreferences != null) {
              try {
                ISecurePreferences node = securePreferences.node(host);
                node.put("user", user, false);
                node.put("password", password, true);
                node.flush();
              } catch (IOException ex) {
                SetupCorePlugin.INSTANCE.log(ex);
              } catch (StorageException ex) {
                SetupCorePlugin.INSTANCE.log(ex);
              }
            }

            authorizations.put(host, reauthorization);
            return reauthorization;
          } else {
            authorizations.put(host, Authorization.UNAUTHORIZEABLE);
            return Authorization.UNAUTHORIZEABLE;
          }
        }
      }

      return currentAuthorization;
    }
  protected void saveSettings(IDialogSettings settings) {
    ISecurePreferences preferences = getPreferences(settings.getName());
    if (preferences == null) {
      // only in case it is not possible to create secured storage in
      // default location -> in that case do not persist settings
      return;
    }

    try {
      preferences.putBoolean(S_SIGN_JARS, fButton.getSelection(), true);
      preferences.put(S_KEYSTORE, fKeystoreText.getText().trim(), true);
      preferences.put(S_ALIAS, fAliasText.getText().trim(), true);
      preferences.put(S_PASSWORD, fPasswordText.getText().trim(), true);
      preferences.put(S_KEYPASS, fKeypassText.getText().trim(), true);

      // bug387565 - for keys which are starting with this bugfix to be
      // stored
      // in secured storage, replace value in settings with empty string
      // to avoid keeping sensitive info in plain text
      String[] obsoleted = new String[] {S_KEYSTORE, S_ALIAS, S_PASSWORD, S_KEYPASS};
      for (String key : obsoleted) {
        if (settings.get(key) != null) {
          settings.put(key, ""); // $NON-NLS-1$
        }
      }
    } catch (StorageException e) {
      PDEPlugin.log(
          "Failed to store JarSigning settings in secured preferences store"); //$NON-NLS-1$
    }
  }
 /**
  * Stores the username and matching password for a particular user.
  *
  * @param forUser the user for whom the credentials are stored
  * @param username the username to store
  * @param password the password to store
  */
 public static void storeCredentials(Optional<String> forUser, String username, char[] password) {
   String user = forUser.orElse(System.getProperty(SYSTEM_PROPERTY_USER_NAME));
   try {
     ISecurePreferences prefs =
         SecurePreferences.getSecurePreferences().node(Activator.ID).node(user);
     if (username == null) {
       return;
     } else {
       prefs.put(PREF_USERNAME, username, false);
     }
     if (password == null) {
       prefs.node(username).remove(PREF_PASSWORD);
     } else {
       ByteBuffer buffer = StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(password));
       byte[] passwordData = Arrays.copyOfRange(buffer.array(), buffer.position(), buffer.limit());
       prefs.node(username).putByteArray(PREF_PASSWORD, passwordData, false);
     }
     SaveRestoreService.LOGGER.log(
         Level.FINE, "Stored new username and password for {0}.", new Object[] {user});
   } catch (StorageException | IOException e) {
     SaveRestoreService.LOGGER.log(Level.WARNING, "Could not store the username and password.", e);
   }
 }
  protected void initialize(IDialogSettings settings) {
    ISecurePreferences preferences = getPreferences(settings.getName());
    if (preferences == null) {
      // only in case it is not possible to create secured storage in
      // default location -> in that case default values are used
      return;
    }

    String keystore = ""; // $NON-NLS-1$
    String keypass = ""; // $NON-NLS-1$
    String alias = ""; // $NON-NLS-1$
    String password = ""; // $NON-NLS-1$
    boolean signJars = false;
    if (preferences.keys().length <= 0) {
      // nothing stored in secured preferences, check settings for values
      // from before bug387565 fix
      keystore = getString(settings, S_KEYSTORE);
      keypass = getString(settings, S_KEYPASS);
      alias = getString(settings, S_ALIAS);
      password = getString(settings, S_PASSWORD);
      signJars = getBoolean(settings, S_SIGN_JARS);
    } else {
      // from secured preferences after bug387565 fix
      keystore = getString(preferences, S_KEYSTORE);
      keypass = getString(preferences, S_KEYPASS);
      alias = getString(preferences, S_ALIAS);
      password = getString(preferences, S_PASSWORD);
      signJars = getBoolean(preferences, S_SIGN_JARS);
    }

    fKeystoreText.setText(keystore);
    fKeypassText.setText(keypass);
    fAliasText.setText(alias);
    fPasswordText.setText(password);
    fButton.setSelection(signJars);
    updateGroup(fButton.getSelection());
  }
  public ProxyPreferencesHandler() {
    try {
      ISecurePreferences securePref = SecurePreferencesFactory.getDefault();
      node = securePref.node("proxy");
      staticMethod = node.get("method", "No proxy");
      staticAuthRequired = false;

      staticHost = node.get("host", "");
      staticPort = node.get("port", "");
      staticAuthRequired = node.getBoolean("authRequired", false);
      if (staticAuthRequired) {
        staticUser = node.get("user", "");
        staticPass = node.get("password", "");
      }
    } catch (StorageException e1) {
      e1.printStackTrace();
      staticMethod = "No proxy";
    }
  }
  private ICredentials getAuthorizationInfo(URI link, String realm) throws CredentialsException {
    ISecurePreferences securePreferences = getSecurePreferences();

    /* Check if Bundle is Stopped */
    if (securePreferences == null) return null;

    /* Return from Equinox Security Storage */
    if (securePreferences.nodeExists(SECURE_FEED_NODE)) { // Global Feed Node
      ISecurePreferences allFeedsPreferences = securePreferences.node(SECURE_FEED_NODE);
      if (allFeedsPreferences.nodeExists(
          EncodingUtils.encodeSlashes(link.toString()))) { // Feed Node
        ISecurePreferences feedPreferences =
            allFeedsPreferences.node(EncodingUtils.encodeSlashes(link.toString()));
        if (feedPreferences.nodeExists(
            EncodingUtils.encodeSlashes(realm != null ? realm : REALM))) { // Realm Node
          ISecurePreferences realmPreferences =
              feedPreferences.node(EncodingUtils.encodeSlashes(realm != null ? realm : REALM));

          try {
            String username = realmPreferences.get(USERNAME, null);
            String password = realmPreferences.get(PASSWORD, null);
            String domain = realmPreferences.get(DOMAIN, null);

            if (username != null && password != null)
              return new Credentials(username, password, domain);
          } catch (StorageException e) {
            throw new CredentialsException(
                Activator.getDefault().createErrorStatus(e.getMessage(), e));
          }
        }
      }
    }

    return null;
  }
  private void internalSetAuthCredentials(
      ICredentials credentials, URI link, String realm, boolean persist)
      throws CredentialsException {

    /* Store Credentials in In-Memory Store */
    if (!persist) {
      fInMemoryStore.put(toCacheKey(link, realm), credentials);
    }

    /* Store Credentials in secure Storage */
    else {
      ISecurePreferences securePreferences = getSecurePreferences();

      /* Check if Bundle is Stopped */
      if (securePreferences == null) return;

      /* Store in Equinox Security Storage */
      ISecurePreferences allFeedsPreferences = securePreferences.node(SECURE_FEED_NODE);
      ISecurePreferences feedPreferences =
          allFeedsPreferences.node(EncodingUtils.encodeSlashes(link.toString()));
      ISecurePreferences realmPreference =
          feedPreferences.node(EncodingUtils.encodeSlashes(realm != null ? realm : REALM));

      IPreferenceScope globalScope = Owl.getPreferenceService().getGlobalScope();

      /* OS Password is only supported on Windows and Mac */
      boolean useOSPassword = globalScope.getBoolean(DefaultPreferences.USE_OS_PASSWORD);
      if (!Platform.OS_WIN32.equals(Platform.getOS())
          && !Platform.OS_MACOSX.equals(Platform.getOS())) useOSPassword = false;

      boolean encryptPW =
          useOSPassword || globalScope.getBoolean(DefaultPreferences.USE_MASTER_PASSWORD);
      try {
        if (credentials.getUsername() != null)
          realmPreference.put(USERNAME, credentials.getUsername(), encryptPW);

        if (credentials.getPassword() != null)
          realmPreference.put(PASSWORD, credentials.getPassword(), encryptPW);

        if (credentials.getDomain() != null)
          realmPreference.put(DOMAIN, credentials.getDomain(), encryptPW);

        realmPreference.flush(); // Flush to disk early
      } catch (StorageException e) {
        throw new CredentialsException(Activator.getDefault().createErrorStatus(e.getMessage(), e));
      } catch (IOException e) {
        throw new CredentialsException(Activator.getDefault().createErrorStatus(e.getMessage(), e));
      }
    }

    /* Uncache */
    removeUnprotected(link, realm);
  }
  /*
   * @see
   * org.rssowl.core.connection.ICredentialsProvider#deleteAuthCredentials(java
   * .net.URI, java.lang.String)
   */
  public synchronized void deleteAuthCredentials(URI link, String realm)
      throws CredentialsException {

    /* Delete from In-Memory Store if present */
    fInMemoryStore.remove(toCacheKey(link, realm));

    /* Delete from Cache */
    removeUnprotected(link, realm);

    /* Check if Bundle is Stopped */
    ISecurePreferences securePreferences = getSecurePreferences();
    if (securePreferences == null) return;

    /* Remove from Equinox Security Storage */
    if (securePreferences.nodeExists(SECURE_FEED_NODE)) { // Global Feed Node
      ISecurePreferences allFeedsPreferences = securePreferences.node(SECURE_FEED_NODE);
      if (allFeedsPreferences.nodeExists(
          EncodingUtils.encodeSlashes(link.toString()))) { // Feed Node
        ISecurePreferences feedPreferences =
            allFeedsPreferences.node(EncodingUtils.encodeSlashes(link.toString()));
        if (feedPreferences.nodeExists(
            EncodingUtils.encodeSlashes(realm != null ? realm : REALM))) { // Realm Node
          ISecurePreferences realmPreferences =
              feedPreferences.node(EncodingUtils.encodeSlashes(realm != null ? realm : REALM));
          realmPreferences.clear();
          realmPreferences.removeNode();
          try {
            feedPreferences.flush();
          } catch (IOException e) {
            throw new CredentialsException(
                Activator.getDefault().createErrorStatus(e.getMessage(), e));
          }
        }
      }
    }
  }