Author: Howard Shank (hgshank@yahoo.com)
@param level Document protecton level
@param pwd Document password - clear text
@since 2.1.1
165408
public boolean setProtection(int level, String pwd) {
    	boolean result = false;
    	if(this.protectionHash == null) {
    		if(!setProtectionLevel(level)) {
    			result = false;
    		}
    		else
    		{
	    		protectionHash = RtfProtection.generateHash(pwd);
	    		result = true;
    		}
    	}
    	else {
	    	if(this.protectionHash.equals(RtfProtection.generateHash(pwd))) {
	    		if(!setProtectionLevel(level)) {
	    			result = false;
	    		}
	    		else
	    		{
		    		protectionHash = RtfProtection.generateHash(pwd);
		    		result = true;
	    		}
	    	}
    	}
    	return result;
    }
89865
static final public String generateHash(String pwd) {
		String encryptedPwd="00000000";
		String password = pwd;
		
		// if there is no password or the length is 0, then skip this and return "00000000" as default
		// otherwise process the password
		if(password != null && password.length() > 0) {
			int hi=0;	// hi order word
			int lo=0;	// lo order word

			// Truncate the password to 15 characters.
			if(password.length() > 15) {
				password = password.substring(0,15);
			}

			// compute key's high-order word
			// initialize to table value
			hi = initialCodeArray[password.length()-1];
			
			int idxF = 0;	// forward index
			int idxR = password.length()-1; // reverse index
			// process each character left to right.
			// check each bit and if it is set, xor the hi word with 
			// the table entry for the position in password and bit position.
			for(; idxF<password.length(); idxF++,idxR--) {
				int ch = password.charAt(idxF);
				if((ch & 0x0001)!= 0) {
					hi = hi ^ encryptionMatrix[idxR][0];
				}
				if((ch & 0x0002)!= 0) {
					hi = hi ^ encryptionMatrix[idxR][1];
				}
				if((ch & 0x0004)!= 0) {
					hi = hi ^ encryptionMatrix[idxR][2];
				}
				if((ch & 0x0008)!= 0) {
					hi = hi ^ encryptionMatrix[idxR][3];
				}
				if((ch & 0x0010)!= 0) {
					hi = hi ^ encryptionMatrix[idxR][4];
				}
				if((ch & 0x0020)!= 0) {
					hi = hi ^ encryptionMatrix[idxR][5];
				}
				if((ch & 0x0040)!= 0) {
					hi = hi ^ encryptionMatrix[idxR][6];
				}
			}
			// Compute Key's low-order word
			idxF = password.length()-1;
			lo = 0;
			// low order word is computed in reverse.
			for(;idxF>= 0; idxF--) {
				int ch = password.charAt(idxF);
				lo = (((lo >> 14) & 0x001) | (( lo << 1) & 0x7fff)) ^ ch;
			}
			// finally incorporate the password length into the low word and use value from formula
			lo = (((lo >> 14) & 0x001) | (( lo << 1) & 0x7fff)) ^ password.length() ^ 0xCE4B;
			
			// correct for little-endian - 
			// Java always uses big-endian. According to tests - RTF wants little-endian but is not documented
			encryptedPwd = Integer.toHexString(lo).substring(2,4) + Integer.toHexString(lo).substring(0,2);
			encryptedPwd += Integer.toHexString(hi).substring(2,4) + Integer.toHexString(hi).substring(0,2);
		}
		return encryptedPwd;
	}
515454
@Override
	public void setText(String text)
	{
		if (password == null) //called from parent ctor
			return;
		if (filterFunction != null)
			text = filterFunction.apply(text);

		password.setLength(0);
		password.append(text);
		updateText();
		selectingText = false;
		if (focused)
			cursor.jumpToEnd();

	}
907485
@Override
	public void log(Level level, String msg, Object param1) {
		
		super.log(level, maskPassword(msg), param1);
	}
189871
public void clearPassword() {
        if (inputPassword != null) {
            for (int i = 0; i < inputPassword.length; i++)
                inputPassword[i] = ' ';
        }
    }
1149071
public String encriptPassword(String password)
    {
        String newpassword = null;
        byte[] defaultBytes = password.getBytes();
        try
        {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(defaultBytes);
            byte messageDigest[] = algorithm.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++)
            {
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            }
            newpassword = hexString.toString();
        }
        catch (NoSuchAlgorithmException e)
        {
            log.error("Error while encripting password {}, caused by : .", password, e);
            throw new PersistenceException(e);
        }
        return newpassword;
    }
1150806
public static boolean check(String passwd, String hashed) {
        try {
            String[] parts = hashed.split("\\$");

            if (parts.length != 5 || !parts[1].equals("s0")) {
                throw new IllegalArgumentException("Invalid hashed value");
            }

            long params = Long.parseLong(parts[2], 16);
            byte[] salt = decode(parts[3].toCharArray());
            byte[] derived0 = decode(parts[4].toCharArray());

            int N = (int) Math.pow(2, params >> 16 & 0xffff);
            int r = (int) params >> 8 & 0xff;
            int p = (int) params      & 0xff;

            byte[] derived1 = SCrypt.scrypt(passwd.getBytes("UTF-8"), salt, N, r, p, 32);

            if (derived0.length != derived1.length) return false;

            int result = 0;
            for (int i = 0; i < derived0.length; i++) {
                result |= derived0[i] ^ derived1[i];
            }
            return result == 0;
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("JVM doesn't support UTF-8?");
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException("JVM doesn't support SHA1PRNG or HMAC_SHA256?");
        }
    }
130501
private void populateMemberData(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException
   {
      m_reader = reader;
      m_file = file;
      m_eventManager = file.getEventManager();
      m_root = root;

      //
      // Retrieve the high level document properties (never encoded)
      //
      Props9 props9 = new Props9(new DocumentInputStream(((DocumentEntry) root.getEntry("Props9"))));
      //System.out.println(props9);

      file.getProjectProperties().setProjectFilePath(props9.getUnicodeString(Props.PROJECT_FILE_PATH));
      m_inputStreamFactory = new DocumentInputStreamFactory(props9);

      //
      // Test for password protection. In the single byte retrieved here:
      //
      // 0x00 = no password
      // 0x01 = protection password has been supplied
      // 0x02 = write reservation password has been supplied
      // 0x03 = both passwords have been supplied
      //
      if ((props9.getByte(Props.PASSWORD_FLAG) & 0x01) != 0)
      {
         // File is password protected for reading, let's read the password
         // and see if the correct read password was given to us.
         String readPassword = MPPUtility.decodePassword(props9.getByteArray(Props.PROTECTION_PASSWORD_HASH), m_inputStreamFactory.getEncryptionCode());
         // It looks like it is possible for a project file to have the password protection flag on without a password. In
         // this case MS Project treats the file as NOT protected. We need to do the same. It is worth noting that MS Project does
         // correct the problem if the file is re-saved (at least it did for me).
         if (readPassword != null && readPassword.length() > 0)
         {
            // See if the correct read password was given
            if (reader.getReadPassword() == null || reader.getReadPassword().matches(readPassword) == false)
            {
               // Passwords don't match
               throw new MPXJException(MPXJException.PASSWORD_PROTECTED_ENTER_PASSWORD);
            }
         }
         // Passwords matched so let's allow the reading to continue.
      }

      m_resourceMap = new HashMap<Integer, ProjectCalendar>();
      m_projectDir = (DirectoryEntry) root.getEntry("   19");
      m_viewDir = (DirectoryEntry) root.getEntry("   29");
      DirectoryEntry outlineCodeDir = (DirectoryEntry) m_projectDir.getEntry("TBkndOutlCode");
      VarMeta outlineCodeVarMeta = new VarMeta9(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry("VarMeta"))));
      m_outlineCodeVarData = new Var2Data(outlineCodeVarMeta, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry("Var2Data"))));
      m_projectProps = new Props9(m_inputStreamFactory.getInstance(m_projectDir, "Props"));
      //MPPUtility.fileDump("c:\\temp\\props.txt", m_projectProps.toString().getBytes());

      m_fontBases = new HashMap<Integer, FontBase>();
      m_taskSubProjects = new HashMap<Integer, SubProject>();

      m_file.getProjectProperties().setMppFileType(Integer.valueOf(9));
      m_file.getProjectProperties().setAutoFilter(props9.getBoolean(Props.AUTO_FILTER));
   }
940394
public static function pwd($length, $chars = null) {
		if ($chars === null) {
			$chars = '234567890abcdefghijkmnopqrstuvwxyz'; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
		}
		$i = 0;
		$password = '';
		$max = strlen($chars) - 1;

		while ($i < $length) {
			$password .= $chars[mt_rand(0, $max)];
			$i++;
		}
		return $password;
	}
1048084
@Override
    public void setPassword(final String password) {
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) {
            SibTr.debug(this, TRACE, "setPassword", "***");
        }
        _password = password;
    }
429185
public boolean removeUpdate(final Password password) throws IOException, ServletException {
	if (!singelton.can(CFMLEngine.CAN_UPDATE, password)) throw new IOException("access denied to update CFMLEngine");
	return removeUpdate();
    }
266917
def check_password(password: str, encrypted: str) -> bool:
    
    # some old passwords have {crypt} in lower case, and passlib wants it to be
    # in upper case.
    if encrypted.startswith("{crypt}"):
        encrypted = "{CRYPT}" + encrypted[7:]
    return pwd_context.verify(password, encrypted)
1012303
function cmd_PWD($fd, $cmd)
    {
        $user = $this->getUser($fd);
        $this->send($fd, "257 \"" . $this->getUserDir($user) . "\" is your current location");
    }
920324
public Response lock(Session session, String path, HierarchicalProperty body, Depth depth, String timeout)
   {

      boolean bodyIsEmpty = (body == null);
      String lockToken;

      //To force read only mode when open a document by user with only read permission
      if(isReadOnly(session, path))
      {
         return Response.status(HTTPStatus.METHOD_NOT_ALLOWED).entity("Permission denied").build();
      }
      try
      {
         WebDavNamespaceContext nsContext = new WebDavNamespaceContext(session);
         try
         {
            Node node = (Node)session.getItem(path);

            if (!node.isNodeType("mix:lockable"))
            {
               if (node.canAddMixin("mix:lockable"))
               {
                  node.addMixin("mix:lockable");
                  session.save();
               }
            }

            Lock lock;
            if (bodyIsEmpty)
            {
               lock = node.getLock();
               lock.refresh();

               body = new HierarchicalProperty(new QName("DAV", "activelock", "D"));
               HierarchicalProperty owner = new HierarchicalProperty(PropertyConstants.OWNER);
               HierarchicalProperty href = new HierarchicalProperty(new QName("D", "href"), lock.getLockOwner());
               body.addChild(owner).addChild(href);
            }
            else
            {
               lock = node.lock((depth.getIntValue() != 1), false);
            }
            lockToken = lock.getLockToken();
         }
         catch (PathNotFoundException pexc)
         {
            lockToken = nullResourceLocks.addLock(session, path);
         }

         LockRequestEntity requestEntity = new LockRequestEntity(body);

         lockToken = WebDavConst.Lock.OPAQUE_LOCK_TOKEN + ":" + lockToken; //NOSONAR

         if (bodyIsEmpty)
         {
            return Response.ok(body(nsContext, requestEntity, depth, lockToken, requestEntity.getOwner(), timeout),
               "text/xml").build();
         }
         else
         {
            return Response
               .ok(body(nsContext, requestEntity, depth, lockToken, requestEntity.getOwner(), timeout), "text/xml")
               .header("Lock-Token", "<" + lockToken + ">").build();
         }
      }
      catch (LockException exc)
      {
         return Response.status(HTTPStatus.LOCKED).entity(exc.getMessage()).build();
      }
      catch (AccessDeniedException exc)
      {
         return Response.status(HTTPStatus.FORBIDDEN).entity(exc.getMessage()).build();
      }
      catch (Exception exc)
      {
         LOG.error(exc.getMessage(), exc);
         return Response.serverError().entity(exc.getMessage()).build();
      }

   }
980151
private static char[] getPassword(TextDevice textDevice, String key) {
        boolean noMatch;
        char[] cred = new char[0];
        char[] passwd1;
        char[] passwd2;
        do {
            passwd1 = textDevice.readPassword("Please enter the password value for %s:", key);
            passwd2 = textDevice.readPassword("Please enter the password value for %s again:", key);
            noMatch = !Arrays.equals(passwd1, passwd2);
            if (noMatch) {
                if (passwd1 != null) {
                    Arrays.fill(passwd1, ' ');
                }
                textDevice.printf("Password entries don't match. Please try again.\n");
            } else {
                if (passwd1.length == 0) {
                    textDevice.printf("An empty password is not valid.  Please try again.\n");
                    noMatch = true;
                } else {
                    cred = passwd1;
                }
            }
            if (passwd2 != null) {
                Arrays.fill(passwd2, ' ');
            }
        } while (noMatch);
        return cred;
    }
58492
function privCheckFormat($p_level=0)
  {
    $v_result = true;

	// ----- Reset the file system cache
    clearstatcache();

    // ----- Reset the error handler
    $this->privErrorReset();

    // ----- Look if the file exits
    if (!is_file($this->zipname)) {
      // ----- Error log
      PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
      return(false);
    }

    // ----- Check that the file is readeable
    if (!is_readable($this->zipname)) {
      // ----- Error log
      PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
      return(false);
    }

    // ----- Check the magic code
    // TBC

    // ----- Check the central header
    // TBC

    // ----- Check each file header
    // TBC

    // ----- Return
    return $v_result;
  }
778307
private void decipherPassword(JournalEntryContext context) {
        String key = JournalHelper.formatDate(context.now());
        String passwordCipher = context.getPassword();
        String clearPassword =
                PasswordCipher.decipher(key, passwordCipher, passwordType);
        context.setPassword(clearPassword);
    }