Android Open Source - android-passwordKeeper Password Document






From Project

Back to project page android-passwordKeeper.

License

The source code is released under:

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions...

If you think the Android project android-passwordKeeper listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/**
 * Copyright 2014 Cody Munger//from w  w  w  .  j a  va  2  s  .c o m
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.munger.passwordkeeper.struct;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.util.Log;

import com.munger.passwordkeeper.MainActivity;

/**
 * A data structure that contains a list of password details and information for encrypting to the file system.
 * @author codymunger
 *
 */
public abstract class PasswordDocument 
{
  /** android context used for saving the files and printing to the log */protected MainActivity context;
  /** encoder used to encrypt the document contents */ protected AES256 encoder;
  /** date of the last load to avoid unneeded decryptions */ protected long lastLoad;

  /** the contents of this document */ public ArrayList<PasswordDetails> details;
  /** unique id for the next detail */ protected int nextIndex;
  public String name;
  
  public PasswordDocument(MainActivity c, String name)
  {
    context = c;
    encoder = null;
    details = new ArrayList<PasswordDetails>();
    lastLoad = 0;
    nextIndex = 0;
    this.name = name;
  }
  
  public PasswordDocument(MainActivity c, String name, String password)
  {
    this(c, name);
    setPassword(password);
  }
  
  public void setIndex(PasswordDetails dets)
  {
    dets.index = Integer.valueOf(nextIndex).toString();
    nextIndex++;
  }
    
  /**
   * Set the password that will protect this document.
   * @param password
   */
  public void setPassword(String password)
  {
    encoder = new AES256(password);
  }
  
  /**
   * Get a human readable version of this document
   */
  public String toString()
  {
    return toString(false);
  }
  
  /**
   * Get and encrypted or human readable string of this document
   * @param encrypt encrypt the document if true, don't if false.
   * @return return the encoded string
   */
  public String toString(boolean encrypt)
  {
    StringBuilder builder = new StringBuilder();
    
    if (encrypt)
    {
      String enc = encoder.encode("test string");
      builder.append(enc).append('\n');
    }
    
    //encrypt the details line by line
    //for easier decryption later
    for (PasswordDetails det : details)
    {
      String line = det.toString();
      
      if (encrypt)
      {
        String enc = encoder.encode(line);
        builder.append(enc).append('\n');
      }
      else
      {
        //separate details by ***** for easier parsing later
        builder.append(line);
      }
    }
    
    return builder.toString();
  }

  /**
   * Decrypt an encoded string
   * @param text the cipertext generated by toString or the plaintext also generated by toString
   * @param decrypt true if the provided text is encrypted, false if it isn't
   */
  public void fromString(String text, boolean decrypt)
  {
    details = new ArrayList<PasswordDetails>();
      if (decrypt)
      {
        //decrypt line by line
        String[] parts = text.split("\n");
        int sz = parts.length;
        for (int i = 0; i < sz; i++)
        {
          if (parts[i].length() > 0)
          {
            String dec = encoder.decode(parts[i]);
                  
            //the first line in an encrypted document should read "test string"
            //otherwise it's an incorrect password or incorrect document
                  if (i == 0)
                  {
                    if (!dec.equals("test string"))
                      return;
                  }
                  //otherwise decode to a PasswordDetails item
                  else
                  {
                    PasswordDetails item = new PasswordDetails();
                    item.fromString(dec);
                    details.add(item);
                  }
              }
          }
      }
      else
      {
        try
        {
          ByteArrayInputStream bais = new ByteArrayInputStream(text.getBytes());
          importFromStream(bais);
          bais.close();
        }
        catch(IOException e){
          Log.v("password", "failed to import encoded string");
        }
      }
  }
  
  abstract public void save();
  abstract public void load(boolean force);
  abstract public void delete();
  abstract public boolean testPassword();


  
  /**
   * Older versions of this program I have running on my laptop export the files in a different format.
   * This function reads files in the older format
   * @param path the file to read data from
   * @throws FileNotFoundException the file couldn't be found
   * @throws IOException the file couldn't be loaded
   */
  public void importFromFile(String path) throws FileNotFoundException, IOException
  {
    FileInputStream fis = new FileInputStream(new File(path));
    
    IOException ret = null;
    
    try
    {
      importFromStream(fis);
    }
    catch(IOException e){
      ret = e;
    }
    finally{
      fis.close();
    }
    
    if (ret != null)
      throw(ret);
  }
    
  /**
   * Older versions of this program I have running on my laptop export the files in a different format.
   * This function reads stream in the older format.
   * Make sure you close your stream.
   * @param stream the stream to read data from
   * @throws IOException the file couldn't be loaded
   */
  public void importFromStream(InputStream stream) throws IOException
  {
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    details = new ArrayList<PasswordDetails>();
    PasswordDetails dets = null;
    PasswordDetails.Pair pair = null;
    
    String line;
    int i = 0;
    IOException ret = null;
    try
    {
      //read from the file line by line
      while ((line = reader.readLine()) != null)
      {
        if (line.length() > 0)
        {
          //create a new set of details if the line starts with Location:
          if (line.startsWith("location: ") && !line.equals("location: "))
          {
            if (dets != null)
            {
              dets.index = Integer.valueOf(details.size() + 1).toString();
              details.add(dets);
              i++;
            }
            
            dets = new PasswordDetails();
            dets.location = line.substring(10);
            dets.name = dets.location;
            dets.index = Integer.valueOf(i).toString();
          }
          else if (line.startsWith("name: "))
          {
            dets.name = line.substring(6);
          }
          //create a new pair for the current details if the line starts with <tab>key:
          else if (line.startsWith("\tkey: "))
          {
            pair = new PasswordDetails.Pair();
            pair.key = line.substring(6);
          }
          //complete the new pair if the line starts with <tab>value:
          else if (line.startsWith("\tvalue: "))
          {
            pair.value = line.substring(8);
            dets.details.add(pair);
          }
          else
          {
            throw new IOException("Couldn't parse import file");
          }
        }
      }
    }
    catch(IOException e){
      ret = e;
    }
    
    if (ret != null)
      throw(ret);
  }
}




Java Source Code List

com.munger.passwordkeeper.MainActivity.java
com.munger.passwordkeeper.SplashScreen.java
com.munger.passwordkeeper.alert.AlertFragment.java
com.munger.passwordkeeper.alert.ConfirmFragment.java
com.munger.passwordkeeper.alert.InputFragment.java
com.munger.passwordkeeper.alert.PasswordFragment.java
com.munger.passwordkeeper.struct.AES256.java
com.munger.passwordkeeper.struct.PasswordDetails.java
com.munger.passwordkeeper.struct.PasswordDocumentDropbox.java
com.munger.passwordkeeper.struct.PasswordDocumentFile.java
com.munger.passwordkeeper.struct.PasswordDocument.java
com.munger.passwordkeeper.view.AboutFragment.java
com.munger.passwordkeeper.view.CreateFileFragment.java
com.munger.passwordkeeper.view.ImportFileFragment.java
com.munger.passwordkeeper.view.SelectFileFragment.java
com.munger.passwordkeeper.view.ViewDetailFragment.java
com.munger.passwordkeeper.view.ViewFileFragment.java
com.munger.passwordkeeper.view.widget.DetailItemWidget.java
com.munger.passwordkeeper.view.widget.FileItemWidget.java
com.munger.passwordkeeper.view.widget.TextInputWidget.java
com.munger.passwordkeeper.view.widget.TextWidget.java