Android Tutorial - Security : MD5

 Md5 sum

 
//com.pommedeterresautee.twoborange.System;

import java.io.BufferedReader;
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.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.util.Log;

public class Md5sum {

  private static final String TAG = "MD5";

  public static boolean checkMD5(String md5, File updateFile) {
    if (md5 == null || md5.equals("") || updateFile == null) {
      Log.e(TAG, "md5 String NULL or UpdateFile NULL");
      return false;
    }

    String calculatedDigest = calculateMD5(updateFile);

    if (calculatedDigest == null) {
      Log.e(TAG, "calculatedDigest NULL");
      return false;
    }

    Log.i(TAG, "Calculated digest: " + calculatedDigest);
    Log.i(TAG, "Provided digest: " + md5);

    return calculatedDigest.equalsIgnoreCase(md5);
  }

  public static String calculateMD5(File updateFile) {
    MessageDigest digest;
    try {
      digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      Log.e(TAG, "Exception while getting Digest", e);
      return null;
    }
    InputStream is;
    try {
      is = new FileInputStream(updateFile);
    } catch (FileNotFoundException e) {
      Log.e(TAG, "Exception while getting FileInputStream", e);
      return null;
    }
    byte[] buffer = new byte[8192];
    int read;
    try {
      while ((read = is.read(buffer)) > 0) {
        digest.update(buffer, 0, read);
      }
      byte[] md5sum = digest.digest();
      BigInteger bigInt = new BigInteger(1, md5sum);
      String output = bigInt.toString(16);
      // Fill to 32 chars
      output = String.format("%32s", output).replace(' ', '0');
      return output;
    } catch (IOException e) {
      throw new RuntimeException("Unable to process file for MD5", e);
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        Log.e(TAG, "Exception on closing MD5 input stream", e);
      }
    }
  }

  public static String getRecoveryMD5() {
    String MD5string = "";
    String recoveryFilename = "/dev/mtd/mtd1";
    try {
      Process p = Runtime.getRuntime().exec("su");
      OutputStream os = p.getOutputStream();
      os.write(("md5sum " + recoveryFilename).getBytes());
      os.flush();
      os.close();
      InputStream is = p.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      String str = br.readLine();
      MD5string = str.split("  ")[0].trim();
      is.close();
      br.close();
      p.destroy();
    } catch (Exception e) {
      Log.e(TAG, "Exception on getting Recovery MD5", e);
      return null;
    }
    Log.i(TAG, "Recovery MD5: " + MD5string);
    return MD5string;
  }
}
MD5 hash generator.
//package com.adam.aslfms.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;


public class MD5 {


  public MD5 () {
    reset();
  }

  public static void main (String[] args){
    if (args.length == 0){
      System.err.println("Please specify a file.");
    } else {
      for (String element: args) {
        try {
          System.out.println(MD5.getHashString(new File(element)) + " " + element);
        } catch (IOException x){
          System.err.println(x.getMessage());
        }
      }
    }
  }


  public byte[] getHash() {
    if (!finalState.valid) {
      finalState.copy(workingState);
      long bitCount = finalState.bitCount;
      // Compute the number of left over bits
      int leftOver = (int) (((bitCount >>> 3)) & 0x3f);
      // Compute the amount of padding to add based on number of left over bits.
      int padlen = (leftOver < 56) ? (56 - leftOver) : (120 - leftOver);
      // add the padding
      update(finalState, padding, 0, padlen);
      // add the length (computed before padding was added)
      update(finalState, encode(bitCount), 0, 8);
      finalState.valid = true;
    }
    // make a copy of the hash before returning it.
    return encode(finalState.state, 16);
  }


  public String getHashString(){
    return toHex(this.getHash());
  }


  public static byte[] getHash(byte[] b){
    MD5 md5 = new MD5();
    md5.update(b);
    return md5.getHash();
  }

  public static String getHashString(byte[] b){
    MD5 md5 = new MD5();
    md5.update(b);
    return md5.getHashString();
  }

  public static byte[] getHash(InputStream in) throws IOException {
    MD5 md5 = new MD5();
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1){
      md5.update(buffer, read);
    }
    return md5.getHash();
  }


  public static String getHashString(InputStream in) throws IOException {
    MD5 md5 = new MD5();
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1){
      md5.update(buffer, read);
    }
    return md5.getHashString();
  }

 
  public static byte[] getHash(File f) throws IOException {
    InputStream is = new FileInputStream(f);
    byte[] hash = getHash(is);
    is.close();
    return hash;
  }


  public static String getHashString(File f) throws IOException {
    InputStream is = new FileInputStream(f);
    String hash = getHashString(is);
    is.close();
    return hash;
  }


  public static byte[] getHash(String s){
    MD5 md5 = new MD5();
    md5.update(s);
    return md5.getHash();
  }

 
  public static String getHashString(String s){
    MD5 md5 = new MD5();
    md5.update(s);
    return md5.getHashString();
  }



  public static byte[] getHash(String s, String enc) throws UnsupportedEncodingException {
    MD5 md5 = new MD5();
    md5.update(s, enc);
    return md5.getHash();
  }


  public static String getHashString(String s, String enc) throws UnsupportedEncodingException {
    MD5 md5 = new MD5();
    md5.update(s, enc);
    return md5.getHashString();
  }


  public void reset() {
    workingState.reset();
    finalState.valid = false;
  }

  @Override public String toString(){
    return getHashString();
  }

  private void update (MD5State state, byte buffer[], int offset, int length) {

    finalState.valid = false;

    // if length goes beyond the end of the buffer, cut it short.
    if ((length + offset) > buffer.length){
      length = buffer.length - offset;
    }

    // compute number of bytes mod 64
    // this is what we have sitting in a buffer
    // that have not been hashed yet
    int index = (int) (state.bitCount >>> 3) & 0x3f;

    // add the length to the count (translate bytes to bits)
    state.bitCount += length << 3;

    int partlen = 64 - index;

    int i = 0;
    if (length >= partlen) {
      System.arraycopy(buffer, offset, state.buffer, index, partlen);
      transform(state, decode(state.buffer, 64, 0));
      for (i = partlen; (i + 63) < length; i+= 64){
        transform(state, decode(buffer, 64, i));
      }
      index = 0;
    }

    // buffer remaining input
    if (i < length) {
      for (int start = i; i < length; i++) {
        state.buffer[index + i - start] = buffer[i + offset];
      }
    }
  }


  public void update (byte buffer[], int offset, int length) {
    update(workingState, buffer, offset, length);
  }


  public void update (byte buffer[], int length) {
    update(buffer, 0, length);
  }

  public void update (byte buffer[]) {
    update(buffer, 0, buffer.length);
  }


  public void update (byte b) {
    byte buffer[] = new byte[1];
    buffer[0] = b;
    update(buffer, 1);
  }

  public void update (String s) {
    update(s.getBytes());
  }


  public void update (String s, String enc) throws UnsupportedEncodingException {
    update(s.getBytes(enc));
  }


  private MD5State workingState = new MD5State();


  private MD5State finalState = new MD5State();


  private int[] decodeBuffer = new int[16];


  private static final byte padding[] = {
    (byte) 0x80, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0,
  };


  private class MD5State {

 
    private boolean valid = true;

 
    private void reset(){
      state[0] = 0x67452301;
      state[1] = 0xefcdab89;
      state[2] = 0x98badcfe;
      state[3] = 0x10325476;

      bitCount = 0;
    }

    private int state[] = new int[4];


    private long bitCount;

  
    private byte buffer[] = new byte[64];

    private MD5State() {
      reset();
    }

   
    private void copy(MD5State from) {
      System.arraycopy(from.buffer, 0, this.buffer, 0, this.buffer.length);
      System.arraycopy(from.state, 0, this.state, 0, this.state.length);
      this.valid = from.valid;
      this.bitCount = from.bitCount;
    }
  }


  private static String toHex(byte hash[]){
    StringBuffer buf = new StringBuffer(hash.length * 2);
    for (byte element: hash) {
      int intVal = element & 0xff;
      if (intVal < 0x10){
        // append a zero before a one digit hex
        // number to make it two digits.
        buf.append("0");
      }
      buf.append(Integer.toHexString(intVal));
    }
    return buf.toString();
  }

  private static int FF (int a, int b, int c, int d, int x, int s, int ac) {
    a += ((b & c) | (~b & d));
    a += x;
    a += ac;
    //return rotateLeft(a, s) + b;
    a = (a << s) | (a >>> (32 - s));
    return a + b;
  }

  private static int GG (int a, int b, int c, int d, int x, int s, int ac) {
    a += ((b & d) | (c & ~d));
    a += x;
    a += ac;
    //return rotateLeft(a, s) + b;
    a = (a << s) | (a >>> (32 - s));
    return a + b;
  }

  private static int HH (int a, int b, int c, int d, int x, int s, int ac) {
    a += (b ^ c ^ d);
    a += x;
    a += ac;
    //return rotateLeft(a, s) + b;
    a = (a << s) | (a >>> (32 - s));
    return a + b;
  }

  private static int II (int a, int b, int c, int d, int x, int s, int ac) {
    a += (c ^ (b | ~d));
    a += x;
    a += ac;
    //return rotateLeft(a, s) + b;
    a = (a << s) | (a >>> (32 - s));
    return a + b;
  }

  private static byte[] encode(long l){
    byte[] out = new byte[8];
    out[0] = (byte) (l & 0xff);
    out[1] = (byte) ((l >>> 8) & 0xff);
    out[2] = (byte) ((l >>> 16) & 0xff);
    out[3] = (byte) ((l >>> 24) & 0xff);
    out[4] = (byte) ((l >>> 32) & 0xff);
    out[5] = (byte) ((l >>> 40) & 0xff);
    out[6] = (byte) ((l >>> 48) & 0xff);
    out[7] = (byte) ((l >>> 56) & 0xff);
    return out;
  }

  private static byte[] encode(int input[], int len){
    byte[] out = new byte[len];
    int i, j;
    for (i = j = 0; j  < len; i++, j += 4) {
      out[j] = (byte) (input[i] & 0xff);
      out[j + 1] = (byte) ((input[i] >>> 8) & 0xff);
      out[j + 2] = (byte) ((input[i] >>> 16) & 0xff);
      out[j + 3] = (byte) ((input[i] >>> 24) & 0xff);
    }
    return out;
  }

  private int[] decode(byte buffer[], int len, int offset){
    int i, j;
    for (i = j = 0; j < len; i++, j += 4) {
      decodeBuffer[i] = (
        (buffer[j + offset] & 0xff)) |
        (((buffer[j + 1 + offset] & 0xff)) << 8) |
        (((buffer[j + 2 + offset] & 0xff)) << 16) |
        (((buffer[j + 3 + offset] & 0xff)) << 24
      );
    }
    return decodeBuffer;
  }

  private static void transform(MD5State state, int[] x){
    int a = state.state[0];
    int b = state.state[1];
    int c = state.state[2];
    int d = state.state[3];

    /* Round 1 */
    a = FF (a, b, c, d, x[ 0],   7, 0xd76aa478); /* 1 */
    d = FF (d, a, b, c, x[ 1],  12, 0xe8c7b756); /* 2 */
    c = FF (c, d, a, b, x[ 2],  17, 0x242070db); /* 3 */
    b = FF (b, c, d, a, x[ 3],  22, 0xc1bdceee); /* 4 */
    a = FF (a, b, c, d, x[ 4],   7, 0xf57c0faf); /* 5 */
    d = FF (d, a, b, c, x[ 5],  12, 0x4787c62a); /* 6 */
    c = FF (c, d, a, b, x[ 6],  17, 0xa8304613); /* 7 */
    b = FF (b, c, d, a, x[ 7],  22, 0xfd469501); /* 8 */
    a = FF (a, b, c, d, x[ 8],   7, 0x698098d8); /* 9 */
    d = FF (d, a, b, c, x[ 9],  12, 0x8b44f7af); /* 10 */
    c = FF (c, d, a, b, x[10],  17, 0xffff5bb1); /* 11 */
    b = FF (b, c, d, a, x[11],  22, 0x895cd7be); /* 12 */
    a = FF (a, b, c, d, x[12],   7, 0x6b901122); /* 13 */
    d = FF (d, a, b, c, x[13],  12, 0xfd987193); /* 14 */
    c = FF (c, d, a, b, x[14],  17, 0xa679438e); /* 15 */
    b = FF (b, c, d, a, x[15],  22, 0x49b40821); /* 16 */

    /* Round 2 */
    a = GG (a, b, c, d, x[ 1],   5, 0xf61e2562); /* 17 */
    d = GG (d, a, b, c, x[ 6],   9, 0xc040b340); /* 18 */
    c = GG (c, d, a, b, x[11],  14, 0x265e5a51); /* 19 */
    b = GG (b, c, d, a, x[ 0],  20, 0xe9b6c7aa); /* 20 */
    a = GG (a, b, c, d, x[ 5],   5, 0xd62f105d); /* 21 */
    d = GG (d, a, b, c, x[10],   9, 0x02441453); /* 22 */
    c = GG (c, d, a, b, x[15],  14, 0xd8a1e681); /* 23 */
    b = GG (b, c, d, a, x[ 4],  20, 0xe7d3fbc8); /* 24 */
    a = GG (a, b, c, d, x[ 9],   5, 0x21e1cde6); /* 25 */
    d = GG (d, a, b, c, x[14],   9, 0xc33707d6); /* 26 */
    c = GG (c, d, a, b, x[ 3],  14, 0xf4d50d87); /* 27 */
    b = GG (b, c, d, a, x[ 8],  20, 0x455a14ed); /* 28 */
    a = GG (a, b, c, d, x[13],   5, 0xa9e3e905); /* 29 */
    d = GG (d, a, b, c, x[ 2],   9, 0xfcefa3f8); /* 30 */
    c = GG (c, d, a, b, x[ 7],  14, 0x676f02d9); /* 31 */
    b = GG (b, c, d, a, x[12],  20, 0x8d2a4c8a); /* 32 */

    /* Round 3 */
    a = HH (a, b, c, d, x[ 5],   4, 0xfffa3942); /* 33 */
    d = HH (d, a, b, c, x[ 8],  11, 0x8771f681); /* 34 */
    c = HH (c, d, a, b, x[11],  16, 0x6d9d6122); /* 35 */
    b = HH (b, c, d, a, x[14],  23, 0xfde5380c); /* 36 */
    a = HH (a, b, c, d, x[ 1],   4, 0xa4beea44); /* 37 */
    d = HH (d, a, b, c, x[ 4],  11, 0x4bdecfa9); /* 38 */
    c = HH (c, d, a, b, x[ 7],  16, 0xf6bb4b60); /* 39 */
    b = HH (b, c, d, a, x[10],  23, 0xbebfbc70); /* 40 */
    a = HH (a, b, c, d, x[13],   4, 0x289b7ec6); /* 41 */
    d = HH (d, a, b, c, x[ 0],  11, 0xeaa127fa); /* 42 */
    c = HH (c, d, a, b, x[ 3],  16, 0xd4ef3085); /* 43 */
    b = HH (b, c, d, a, x[ 6],  23, 0x04881d05); /* 44 */
    a = HH (a, b, c, d, x[ 9],   4, 0xd9d4d039); /* 45 */
    d = HH (d, a, b, c, x[12],  11, 0xe6db99e5); /* 46 */
    c = HH (c, d, a, b, x[15],  16, 0x1fa27cf8); /* 47 */
    b = HH (b, c, d, a, x[ 2],  23, 0xc4ac5665); /* 48 */

    /* Round 4 */
    a = II (a, b, c, d, x[ 0],   6, 0xf4292244); /* 49 */
    d = II (d, a, b, c, x[ 7],  10, 0x432aff97); /* 50 */
    c = II (c, d, a, b, x[14],  15, 0xab9423a7); /* 51 */
    b = II (b, c, d, a, x[ 5],  21, 0xfc93a039); /* 52 */
    a = II (a, b, c, d, x[12],   6, 0x655b59c3); /* 53 */
    d = II (d, a, b, c, x[ 3],  10, 0x8f0ccc92); /* 54 */
    c = II (c, d, a, b, x[10],  15, 0xffeff47d); /* 55 */
    b = II (b, c, d, a, x[ 1],  21, 0x85845dd1); /* 56 */
    a = II (a, b, c, d, x[ 8],   6, 0x6fa87e4f); /* 57 */
    d = II (d, a, b, c, x[15],  10, 0xfe2ce6e0); /* 58 */
    c = II (c, d, a, b, x[ 6],  15, 0xa3014314); /* 59 */
    b = II (b, c, d, a, x[13],  21, 0x4e0811a1); /* 60 */
    a = II (a, b, c, d, x[ 4],   6, 0xf7537e82); /* 61 */
    d = II (d, a, b, c, x[11],  10, 0xbd3af235); /* 62 */
    c = II (c, d, a, b, x[ 2],  15, 0x2ad7d2bb); /* 63 */
    b = II (b, c, d, a, x[ 9],  21, 0xeb86d391); /* 64 */

    state.state[0] += a;
    state.state[1] += b;
    state.state[2] += c;
    state.state[3] += d;
  }
}

md5 sum and hmac Sha1 Digest

//package org.andlib.helpers;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAKeyGenParameterSpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


/**
 * 
 * @author meinside@gmail.com
 * @since 09.11.24.
 * 
 * last update 10.04.13.
 *
 */
final  class StringCodec
{
  /**
   * 
   * @param original
   * @return null if fails
   */
  public static String urlencode(String original)
  {
    try
    {
      //return URLEncoder.encode(original, "utf-8");
      //fixed: to comply with RFC-3986
      return URLEncoder.encode(original, "utf-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }
    catch(UnsupportedEncodingException e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * 
   * @param encoded
   * @return null if fails
   */
  public static String urldecode(String encoded)
  {
    try
    {
      return URLDecoder.decode(encoded, "utf-8");
    }
    catch(UnsupportedEncodingException e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * 
   * @param original
   * @param key
   * @return null if fails
   */
  public static String hmacSha1Digest(String original, String key)
  {
    return hmacSha1Digest(original.getBytes(), key.getBytes());
  }
  
  /**
   * 
   * @param original
   * @param key
   * @return null if fails
   */
  public static String hmacSha1Digest(byte[] original, byte[] key)
  {
    try
    {
      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(new SecretKeySpec(key, "HmacSHA1"));
      byte[] rawHmac = mac.doFinal(original);
      return new String(Base64Coder.encode(rawHmac));
    }
    catch (Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * 
   * @param original
   * @return null if fails
   */
  public static String md5sum(byte[] original)
  {
    try
    {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(original, 0, original.length);
      StringBuffer md5sum = new StringBuffer(new BigInteger(1, md.digest()).toString(16));
      while(md5sum.length() < 32)
        md5sum.insert(0, "0");
      return md5sum.toString();
    }
    catch(NoSuchAlgorithmException e)
    {
      //Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * 
   * @param original
   * @return null if fails
   */
  public static String md5sum(String original)
  {
    return md5sum(original.getBytes());
  }
  
  /**
   * AES encrypt function
   * 
   * @param original
   * @param key 16, 24, 32 bytes available
   * @param iv initial vector (16 bytes) - if null: ECB mode, otherwise: CBC mode
   * @return
   */
  public static byte[] aesEncrypt(byte[] original, byte[] key, byte[] iv)
  {
    if(key == null || (key.length != 16 && key.length != 24 && key.length != 32))
    {
    //  Logger.e("key's bit length is not 128/192/256");
      return null;
    }
    if(iv != null && iv.length != 16)
    {
    //  Logger.e("iv's bit length is not 16");
      return null;
    }

    try
    {
      SecretKeySpec keySpec = null;
      Cipher cipher = null;
      if(iv != null)
      {
        keySpec = new SecretKeySpec(key, "AES/CBC/PKCS7Padding");
        cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
      }
      else  //if(iv == null)
      {
        keySpec = new SecretKeySpec(key, "AES/ECB/PKCS7Padding");
        cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
      }

      return cipher.doFinal(original);
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }

  /**
   * AES decrypt function
   * 
   * @param encrypted
   * @param key 16, 24, 32 bytes available
   * @param iv initial vector (16 bytes) - if null: ECB mode, otherwise: CBC mode
   * @return
   */
  public static byte[] aesDecrypt(byte[] encrypted, byte[] key, byte[] iv)
  {
    if(key == null || (key.length != 16 && key.length != 24 && key.length != 32))
    {
    //  Logger.e("key's bit length is not 128/192/256");
      return null;
    }
    if(iv != null && iv.length != 16)
    {
    //  Logger.e("iv's bit length is not 16");
      return null;
    }

    try
    {
      SecretKeySpec keySpec = null;
      Cipher cipher = null;
      if(iv != null)
      {
        keySpec = new SecretKeySpec(key, "AES/CBC/PKCS7Padding");
        cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
      }
      else  //if(iv == null)
      {
        keySpec = new SecretKeySpec(key, "AES/ECB/PKCS7Padding");
        cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
      }

      return cipher.doFinal(encrypted);
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * generates RSA key pair
   * 
   * @param keySize
   * @param publicExponent public exponent value (can be RSAKeyGenParameterSpec.F0 or F4)
   * @return
   */
  public static KeyPair generateRsaKeyPair(int keySize, BigInteger publicExponent)
  {
    KeyPair keys = null;
    try
    {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
      RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(keySize, publicExponent);
      keyGen.initialize(spec);
      keys = keyGen.generateKeyPair();
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return keys;
  }
  
  /**
   * generates a RSA public key with given modulus and public exponent
   * 
   * @param modulus (must be positive? don't know exactly)
   * @param publicExponent
   * @return
   */
  public static PublicKey generateRsaPublicKey(BigInteger modulus, BigInteger publicExponent)
  {
    try
    {
      return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * generates a RSA private key with given modulus and private exponent
   * 
   * @param modulus (must be positive? don't know exactly)
   * @param privateExponent
   * @return
   */
  public static PrivateKey generateRsaPrivateKey(BigInteger modulus, BigInteger privateExponent)
  {
    try
    {
      return KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * RSA encrypt function (RSA / ECB / PKCS1-Padding)
   * 
   * @param original
   * @param key
   * @return
   */
  public static byte[] rsaEncrypt(byte[] original, PublicKey key)
  {
    try
    {
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      cipher.init(Cipher.ENCRYPT_MODE, key);
      return cipher.doFinal(original);
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }
  
  /**
   * RSA decrypt function (RSA / ECB / PKCS1-Padding)
   * 
   * @param encrypted
   * @param key
   * @return
   */
  public static byte[] rsaDecrypt(byte[] encrypted, PrivateKey key)
  {
    try
    {
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      cipher.init(Cipher.DECRYPT_MODE, key);
      return cipher.doFinal(encrypted);
    }
    catch(Exception e)
    {
    //  Logger.e(e.toString());
    }
    return null;
  }

  /**
   * converts given byte array to a hex string
   * 
   * @param bytes
   * @return
   */
  public static String byteArrayToHexString(byte[] bytes)
  {
    StringBuffer buffer = new StringBuffer();
    for(int i=0; i<bytes.length; i++)
    {
      if(((int)bytes[i] & 0xff) < 0x10)
        buffer.append("0");
      buffer.append(Long.toString((int) bytes[i] & 0xff, 16));
    }
    return buffer.toString();
  }
  
  /**
   * converts given hex string to a byte array
   * (ex: "0D0A" => {0x0D, 0x0A,})
   * 
   * @param str
   * @return
   */
  public static final byte[] hexStringToByteArray(String str)
  {
    int i = 0;
    byte[] results = new byte[str.length() / 2];
    for (int k = 0; k < str.length();)
    {
      results[i] = (byte)(Character.digit(str.charAt(k++), 16) << 4);
      results[i] += (byte)(Character.digit(str.charAt(k++), 16));
      i++;
    } 
    return results;
  }
}


class Base64Coder {

  //Mapping table from 6-bit nibbles to Base64 characters.
  private static char[]    map1 = new char[64];
  static {
     int i=0;
     for (char c='A'; c<='Z'; c++) map1[i++] = c;
     for (char c='a'; c<='z'; c++) map1[i++] = c;
     for (char c='0'; c<='9'; c++) map1[i++] = c;
     map1[i++] = '+'; map1[i++] = '/';
    }
  
  //Mapping table from Base64 characters to 6-bit nibbles.
  private static byte[]    map2 = new byte[128];
  static {
    for (int i=0; i<map2.length; i++) map2[i] = -1;
    for (int i=0; i<64; i++) map2[map1[i]] = (byte)i;
  }
  
  /**
   * Encodes a string into Base64 format.
   * No blanks or line breaks are inserted.
   * @param s  a String to be encoded.
   * @return   A String with the Base64 encoded data.
   */
  public static String encodeString (String s) {
    return new String(encode(s.getBytes()));
  }
  
  /**
   * Encodes a byte array into Base64 format.
   * No blanks or line breaks are inserted.
   * @param in  an array containing the data bytes to be encoded.
   * @return    A character array with the Base64 encoded data.
   */
  public static char[] encode (byte[] in) {
    return encode(in,in.length);
  }
  
  /**
   * Encodes a byte array into Base64 format.
   * No blanks or line breaks are inserted.
   * @param in   an array containing the data bytes to be encoded.
   * @param iLen number of bytes to process in <code>in</code>.
   * @return     A character array with the Base64 encoded data.
   */
  public static char[] encode (byte[] in, int iLen) {
    int oDataLen = (iLen*4+2)/3;       // output length without padding
    int oLen = ((iLen+2)/3)*4;         // output length including padding
    char[] out = new char[oLen];
    int ip = 0;
    int op = 0;
    while (ip < iLen) {
      int i0 = in[ip++] & 0xff;
      int i1 = ip < iLen ? in[ip++] & 0xff : 0;
      int i2 = ip < iLen ? in[ip++] & 0xff : 0;
      int o0 = i0 >>> 2;
      int o1 = ((i0 &   3) << 4) | (i1 >>> 4);
      int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
      int o3 = i2 & 0x3F;
      out[op++] = map1[o0];
      out[op++] = map1[o1];
      out[op] = op < oDataLen ? map1[o2] : '='; op++;
      out[op] = op < oDataLen ? map1[o3] : '='; op++; }
    return out; 
  }
  
  /**
   * Decodes a string from Base64 format.
   * @param s  a Base64 String to be decoded.
   * @return   A String containing the decoded data.
   * @throws   IllegalArgumentException if the input is not valid Base64 encoded data.
   */
  public static String decodeString (String s) {
    return new String(decode(s)); 
  }
  
  /**
   * Decodes a byte array from Base64 format.
   * @param s  a Base64 String to be decoded.
   * @return   An array containing the decoded data bytes.
   * @throws   IllegalArgumentException if the input is not valid Base64 encoded data.
   */
  public static byte[] decode (String s) {
    return decode(s.toCharArray()); 
  }
  
  /**
   * Decodes a byte array from Base64 format.
   * No blanks or line breaks are allowed within the Base64 encoded data.
   * @param in  a character array containing the Base64 encoded data.
   * @return    An array containing the decoded data bytes.
   * @throws    IllegalArgumentException if the input is not valid Base64 encoded data.
   */
  public static byte[] decode (char[] in) {
    int iLen = in.length;
    if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
    while (iLen > 0 && in[iLen-1] == '=') iLen--;
    int oLen = (iLen*3) / 4;
    byte[] out = new byte[oLen];
    int ip = 0;
    int op = 0;
    while (ip < iLen) {
      int i0 = in[ip++];
      int i1 = in[ip++];
      int i2 = ip < iLen ? in[ip++] : 'A';
      int i3 = ip < iLen ? in[ip++] : 'A';
      if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
        throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
      int b0 = map2[i0];
      int b1 = map2[i1];
      int b2 = map2[i2];
      int b3 = map2[i3];
      if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
        throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
      int o0 = ( b0       <<2) | (b1>>>4);
      int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
      int o2 = ((b2 &   3)<<6) |  b3;
      out[op++] = (byte)o0;
      if (op<oLen) out[op++] = (byte)o1;
      if (op<oLen) out[op++] = (byte)o2;
    }
    return out;
  }
  
  //Dummy constructor.
  private Base64Coder() {}

} // end class Base64Coder

Create Md5 Checksum

 
//package com.si.anddos.utils;

import java.io.BufferedReader;
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.security.MessageDigest;
import java.util.Date;

/**
 * 
 * @author Carlos Martinez
 */
class Utils {
  // --------- Carlos Martinez -------------------
  public static String inputStreamAsString(InputStream stream)
      throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(stream,
        "UTF-8"));
    StringBuilder sb = new StringBuilder();
    String line = null;

    while ((line = br.readLine()) != null) {
      sb.append(line).append('\n');
    }

    br.close();

    return sb.toString();
  }

  // ----------- Carlos Martinez ----------------------
  public static String parseLastValueStr(String s, String oddelovac) {
    return s.substring(s.lastIndexOf(oddelovac) + 1);
  }

  public static long getDateLong() {
    Date d = new Date();
    return d.getTime();
  }

  public static String getMD5(File file) throws FileNotFoundException,
      IOException {


    try {
      return getMD5Checksum(file.getAbsolutePath());
    } catch (Exception e) {
      e.printStackTrace();
    }
    
    return "";
  }

  public static byte[] createChecksum(String filename) throws Exception {
    InputStream fis = new FileInputStream(filename);

    byte[] buffer = new byte[1024];
    MessageDigest complete = MessageDigest.getInstance("MD5");
    int numRead;
    do {
      numRead = fis.read(buffer);
      if (numRead > 0) {
        complete.update(buffer, 0, numRead);
      }
    } while (numRead != -1);
    fis.close();
    return complete.digest();
  }

  // see this How-to for a faster way to convert
  // a byte array to a HEX string
  public static String getMD5Checksum(String filename) throws Exception {
    byte[] b = createChecksum(filename);
    String result = "";
    for (int i = 0; i < b.length; i++) {
      result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    return result;
  }
}

MD5 Hash

 
// Created by plusminus on 10:35:21 - 01.02.2009
//package org.andnav2.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


class MD5 {

  public static String hash(final String in) {
    if(in == null) {
      throw new IllegalArgumentException("'in' has to be != null");
    }
    try {
      final MessageDigest md5 = MessageDigest.getInstance("MD5");
      if(md5 == null) {
        return in;
      }

      try {
        md5.update(in.getBytes("UTF-8"));
      } catch (final UnsupportedEncodingException e) {
        return in;
      }

      return new BigInteger(1,md5.digest()).toString(16);
    } catch (final NoSuchAlgorithmException ex) {
      return in;
    }
  }
}

MD5 String Util

 

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

 class MD5StringUtil
{
    private static final MessageDigest digest;

    static
    {
        try
        {
            digest = MessageDigest.getInstance("MD5");
        }
        catch (NoSuchAlgorithmException e)
        {
            throw new RuntimeException(e);
        }
    }

    public static String md5StringFor(String s)
    {
        final byte[] hash = digest.digest(s.getBytes());
        final StringBuilder builder = new StringBuilder();
        for (byte b : hash)
        {
            builder.append(Integer.toString(b & 0xFF, 16));    
        }
        return builder.toString();
    }
}

Download from URL and MD5 check

 

//package com.IsraelPack;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.util.Log;

public class Utils {
  public static boolean DownloadFromUrl(String url, String fileName) {
    try {
      BufferedInputStream in = new BufferedInputStream(new URL(url)
          .openStream());
      FileOutputStream fos = new FileOutputStream(fileName);
      BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
      byte[] data = new byte[1024];
      int x = 0;
      while ((x = in.read(data, 0, 1024)) >= 0) {
        bout.write(data, 0, x);
      }
      bout.close();
      in.close();
    } catch (IOException e) {
      Log.e("IsraelPack", e.getMessage());
      return false;
    }
    return true;
  }

  public static boolean checkMD5(String md5, String fileName) {
    if (md5 == null || md5 == "" || fileName == null) {
      return false;
    }
    String calculatedDigest = calculateMD5(fileName);
    if (calculatedDigest == null) {
      return false;
    }
    return calculatedDigest.equalsIgnoreCase(md5);
  }

  public static String calculateMD5(String fileName) {
    File updateFile = new File(fileName);
    MessageDigest digest = null;
    try {
      digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      return null;
    }
    InputStream is = null;
    try {
      is = new FileInputStream(updateFile);
    } catch (FileNotFoundException e) {
      return null;
    }
    byte[] buffer = new byte[8192];
    int read = 0;
    try {
      while ((read = is.read(buffer)) > 0) {
        digest.update(buffer, 0, read);
      }
      byte[] md5sum = digest.digest();
      BigInteger bigInt = new BigInteger(1, md5sum);
      String output = bigInt.toString(16);
      // Fill to 32 chars
      output = String.format("%32s", output).replace(' ', '0');
      return output;
    } catch (IOException e) {
      throw new RuntimeException("Unable to process file for MD5", e);
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        throw new RuntimeException(
            "Unable to close input stream for MD5 calculation", e);
      }
    }
  }

  public static String readFileAsString(String filePath) {
    try {
      StringBuffer fileData = new StringBuffer(1000);
      BufferedReader reader;

      reader = new BufferedReader(new FileReader(filePath));
      char[] buf = new char[1024];
      int numRead = 0;
      while ((numRead = reader.read(buf)) != -1) {
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
        buf = new char[1024];
      }
      reader.close();
      return fileData.toString();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
}

Md5 Hash and MessageDigest

 
//package com.megagoodsoftware.smugmug.util;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.util.Log;

public class SmugMugUtil {
  public static String getMd5Hash(byte[] input) {
        try     {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(input);
                return getMd5Hash(md);
        } catch(NoSuchAlgorithmException e) {
                Log.e("MD5", e.getMessage());
                return null;
        }
  }

  public static String getMd5Hash(String string) {
    return getMd5Hash(string.getBytes());
  }
  
  public static String getMd5Hash(MessageDigest digest) {
      BigInteger number = new BigInteger(1, digest.digest());
      String md5 = number.toString(16);
           
      // need to pad the hash
      while (md5.length() < 32)
        md5 = "0" + md5;
           
      return md5;
  }
  
  public static String getMd5Hash(InputStream is) {
    byte[] buffer = new byte[8192];
    int read = 0;
    try {
      MessageDigest digest = MessageDigest.getInstance("MD5");
      while( (read = is.read(buffer)) > 0) {
        digest.update(buffer, 0, read);
      }
      return getMd5Hash(digest);
    } catch(IOException e) {
      throw new RuntimeException("Unable to process file for MD5", e);
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException("Unable to process file for MD5", e);
    }
  }
  
}

Md5 String

//package com.renren.api.connect.android;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;


 class Util {
    public static String md5(String string) {
      if (string == null || string.trim().length() < 1) {
        return null;
      }
      try {
        return getMD5(string.getBytes("UTF-8"));
      } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
      }
    }

    private static String getMD5(byte[] source) {
      try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        StringBuffer result = new StringBuffer();
        for (byte b : md5.digest(source)) {
          result.append(Integer.toHexString((b & 0xf0) >>> 4));
          result.append(Integer.toHexString(b & 0x0f));
        }
        return result.toString();
      } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
      }
    }

}