Exemple #1
0
  public FileData decryptFile(FileData fd) throws IOException {
    ByteArrayInputStream input = fd.getInputStream();
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    BASE64Decoder base64 = new BASE64Decoder();
    byte[] bytearr = base64.decodeBuffer(input);
    input = new ByteArrayInputStream(bytearr);

    Cipher cipher = null;
    try {
      cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    } catch (Exception e) {
      throw new IOException(e);
    }

    try {
      cipher.init(Cipher.DECRYPT_MODE, key);
    } catch (Exception e) {
      throw new IOException(e);
    }

    int length = -1;
    CipherInputStream stream = new CipherInputStream(input, cipher);
    while ((length = stream.read(bytearr)) != -1) {
      output.write(bytearr, 0, length);
    }
    output.close();

    String path = fd.getPath().replaceAll("\\.(.*)_enc", "\\.$1");
    return new FileData(path, output.toByteArray());
  }
Exemple #2
0
  /** This encryption/decryption code doesn't match outputs with the Python code. It needs fixed. */
  public byte[] decrypt(byte[] encryptedBytes) { // , byte[] iv
    String output = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {

      SecretKeySpec key = generatekey();

      // Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      // IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
      // decryptCipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
      Cipher decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      decryptCipher.init(Cipher.DECRYPT_MODE, key);

      outputStream = new ByteArrayOutputStream();
      ByteArrayInputStream inStream = new ByteArrayInputStream(encryptedBytes);
      CipherInputStream cipherInputStream = new CipherInputStream(inStream, decryptCipher);
      byte[] buf = new byte[1024];
      int bytesRead;
      while ((bytesRead = cipherInputStream.read(buf)) >= 0) {
        outputStream.write(buf, 0, bytesRead);
      }

      output = new String(outputStream.toByteArray(), "UTF-8");
      Log.d(TAG, output);
      cipherInputStream.close();
      inStream.close();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      // Log.e(TAG,e.getCause().toString());
      Log.e(TAG, e.getMessage());
      return null;
    } /*catch (InvalidAlgorithmParameterException e) {
      	e.printStackTrace();
      	return null;
      }*/ catch (NoSuchPaddingException e) {
      e.printStackTrace();
      return null;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    }

    // return output;
    return outputStream.toByteArray();
  }
  String getDecryptedData(RSAPrivateKey key)
      throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
          NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
    cipher.init(Cipher.DECRYPT_MODE, key);
    CipherInputStream cipherInputStream =
        new CipherInputStream(new FileInputStream(getFilePath()), cipher);
    byte[] roundTrippedBytes = new byte[1000]; // TODO: dynamically resize
    // as we get more data

    int index = 0;
    int nextByte;
    while ((nextByte = cipherInputStream.read()) != -1) {
      roundTrippedBytes[index] = (byte) nextByte;
      index++;
    }
    cipherInputStream.close();
    return new String(roundTrippedBytes, 0, index, "UTF-8");
  }
  private void runTest(String name) throws Exception {
    String lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789";
    KeyGenerator kGen;

    if (name.indexOf('/') < 0) {
      kGen = KeyGenerator.getInstance(name, "BC");
    } else {
      kGen = KeyGenerator.getInstance(name.substring(0, name.indexOf('/')), "BC");
    }

    Cipher in = Cipher.getInstance(name, "BC");
    Cipher out = Cipher.getInstance(name, "BC");
    Key key = kGen.generateKey();
    ByteArrayInputStream bIn = new ByteArrayInputStream(lCode.getBytes());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    in.init(Cipher.ENCRYPT_MODE, key);
    if (in.getIV() != null) {
      out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(in.getIV()));
    } else {
      out.init(Cipher.DECRYPT_MODE, key);
    }

    CipherInputStream cIn = new CipherInputStream(bIn, in);
    CipherOutputStream cOut = new CipherOutputStream(bOut, out);

    int c;

    while ((c = cIn.read()) >= 0) {
      cOut.write(c);
    }

    cIn.close();

    cOut.flush();
    cOut.close();

    String res = new String(bOut.toByteArray());

    if (!res.equals(lCode)) {
      fail("Failed - decrypted data doesn't match.");
    }
  }
  public static String decrypt(String cryptedText, String password) {
    String dec = "";
    try {
      // convert to byte array

      PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
      // METHOD = "PBEWITHSHA-1AND128BITAES-CBC-BC";
      // //PBEWITHSHA256AND128BITAES-CBC-BC";//PBEWithMD5AndDES";
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(METHOD);
      SecretKey secretKey = keyFactory.generateSecret(keySpec);
      PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);
      cipher = Cipher.getInstance(METHOD);
      cipher.init(Cipher.DECRYPT_MODE, secretKey, parameterSpec);
      decryptedText = new ByteArrayInputStream(cryptedText.getBytes());
      CipherInputStream in = new CipherInputStream(decryptedText, cipher);
      byte contents = (byte) in.read();
      char c = 82;
      while (contents != -1) {
        fileBytes.add(new Byte(contents));
        c = (char) Integer.parseInt(fileBytes.get(fileBytes.size() - 1) + "");
        dec = dec + c;
        contents = (byte) in.read();
      }
      in.close();
    } catch (IOException ex) {
      Logger.getLogger(Logic.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
      Logger.getLogger(Logic.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
      Logger.getLogger(Logic.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
      Logger.getLogger(Logic.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(Logic.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
      Logger.getLogger(Logic.class.getName()).log(Level.SEVERE, null, ex);
    }
    return dec;
  }
  /**
   * Read crypted data from the highscore-file.
   *
   * @return the decrypted data in the file.
   * @see ObjectInputStream#readObject
   */
  @SuppressWarnings("unchecked")
  private void readHighscore() {
    FileInputStream fis = null;
    CipherInputStream cis = null;
    ObjectInputStream ois = null;
    entries = new ArrayList<HighscoreEntry>();
    try {
      fis = new FileInputStream(GameConstants.HIGHSCORE_FILE_NAME);
      cis = new CipherInputStream(fis, dcipher);
      ois = new ObjectInputStream(cis);

      this.entries = (ArrayList<HighscoreEntry>) ois.readObject();

      ois.close();
      cis.close();
      fis.close();
    } catch (FileNotFoundException e) {
      entries = new ArrayList<HighscoreEntry>();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) throws Exception {
    // prompt user to enter a port number

    System.out.print("Enter the port number: ");
    Scanner scan = new Scanner(System.in);
    int port = scan.nextInt();
    scan.nextLine();
    System.out.print("Enter the host name: ");
    String hostName = scan.nextLine();

    // Initialize a key pair generator with the SKIP parameters we sepcified, and genrating a pair
    // This will take a while: 5...15 seconrds

    System.out.println("Generating a Diffie-Hellman keypair: ");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
    kpg.initialize(PARAMETER_SPEC);
    KeyPair keyPair = kpg.genKeyPair();
    System.out.println("key pair has been made...");

    // one the key pair has been generated, we want to listen on
    // a given port for a connection to come in
    // once we get a connection, we will get two streams, One for input
    // and one for output
    // open a port and wait for a connection

    ServerSocket ss = new ServerSocket(port);
    System.out.println("Listeining on port " + port + " ...");
    Socket socket = ss.accept();

    // use to output and input primitive data type

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());

    // next thing to do is send our public key and receive client's
    // this corresponds to server step 3 and step 4 in the diagram

    System.out.println("Sending my public key...");
    byte[] keyBytes = keyPair.getPublic().getEncoded();
    out.writeInt(keyBytes.length);
    out.write(keyBytes);
    System.out.println("Server public key bytes: " + CryptoUtils.toHex(keyBytes));

    // receive the client's public key

    System.out.println("Receiving client's public key...");
    DataInputStream in = new DataInputStream(socket.getInputStream());
    keyBytes = new byte[in.readInt()];
    in.readFully(keyBytes);

    // create client's public key

    KeyFactory kf = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes);
    PublicKey clientPublicKey = kf.generatePublic(x509Spec);

    // print out client's public key bytes

    System.out.println(
        "Client public key bytes: " + CryptoUtils.toHex(clientPublicKey.getEncoded()));

    // we can now use the client's public key and
    // our own private key to perform the key agreement

    System.out.println("Performing the key agreement ... ");
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(clientPublicKey, true);

    // in a chat application, each character is sendt over the wire, separetly encrypted,
    // Instead of using ECB, we are goin to use CFB, with a block size of 8 bits(1byte)
    // to send each character. We will encrypt the same character in a different way
    // each time. But in order to use CFB8, we need an IVof 8 bytes. We will create
    // that IV randomly and and send it to the client. It doesn't matter if somoene
    // eavesdrops on the IV when it is sent over the wire. it's not sensitive info

    // creating the IV and sending it corresponds to step 6 and 7

    byte[] iv = new byte[8];
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(iv);
    out.write(iv);

    // we generate the secret byte array we share with the client and use it
    // to create the session key (Step 8)

    byte[] sessionKeyBytes = ka.generateSecret();

    // create the session key

    SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec DESedeSpec = new DESedeKeySpec(sessionKeyBytes);
    SecretKey sessionKey = skf.generateSecret(DESedeSpec);

    // printout session key bytes

    System.out.println("Session key bytes: " + CryptoUtils.toHex(sessionKey.getEncoded()));

    // now use tha that session key and IV to create a CipherInputStream. We will use them to read
    // all character
    // that are sent to us by the client

    System.out.println("Creating the cipher stream ...");
    Cipher decrypter = Cipher.getInstance("DESede/CFB8/NoPadding");
    IvParameterSpec spec = new IvParameterSpec(iv);
    decrypter.init(Cipher.DECRYPT_MODE, sessionKey, spec);
    CipherInputStream cipherIn = new CipherInputStream(socket.getInputStream(), decrypter);

    // we just keep reading the input and print int to the screen, until -1 sent over

    int theCharacter = 0;
    theCharacter = cipherIn.read();
    while (theCharacter != -1) {
      System.out.print((char) theCharacter);
      theCharacter = cipherIn.read();
    }
    // once -1 is received we want to close up our stream and exit

    cipherIn.close();
    in.close();
    out.close();
    socket.close();
  }