Showing posts with label AES. Show all posts
Showing posts with label AES. Show all posts

Thursday, March 15, 2012

How to generate md5 hash in Android?


The MD5 Message-Digest Algorithm is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. Specified in RFC 1321, MD5 has been employed in a wide variety of security applications, and is also commonly used to check data integrity. However, it has been shown that MD5 is not collision resistant; as such, MD5 is not suitable for applications like SSL certificates or digital signatures that rely on this property. An MD5 hash is typically expressed as a 32-digit hexadecimal number.

package com.as400samplecode;

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

public class MD5Hash {

    public static void main(String[] args) {
      
        String s = "SecretKey20111013000";
        String  res = md5(s);
        System.out.println(res);

    }

    private static String md5(String s) { try {
      
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

         // Create Hex String
         StringBuffer hexString = new StringBuffer();
         for (int i=0; i<messageDigest.length; i++)
             hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
        return hexString.toString();

     } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
     }
     return "";

    }

Monday, February 13, 2012

AES Encryption/Descryption Between Android and C#?


Now a days people are more concerning about securing the data while transmitting over the http.Here is a code snippets which shows that how the Data in encrypted using Two different Keys called a Pass Phrase and Salt Key and Encrypt the data Also a code to decrypt the encrypted data in C# using the same Pass Phrase and Salt key.
Here Salt Key is just a Name give to a IVParamSpec Parameter.
//Android Code 

public class MyCrypto {
    public static final String TAG = "crypto";

    private static Cipher aesCipher;
    private static SecretKey secretKey;
    private static IvParameterSpec ivParameterSpec;

    private static String TRANSFORMATION_CIPHER = "AES/CBC/PKCS5Padding";
    private static String ALGORITHM_CIPHER = "AES";
    // Replace below with a 16-byte key, share between Java and C#
    private static byte[] saltSecretKey = {0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 
0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f};

    private static String ALGORITHM_DIGEST = "MD5";

    public MyCrypto(String passphrase) {
        byte[] passwordKey = encodeDigest(passphrase);
        try {
            aesCipher = Cipher.getInstance(TRANSFORMATION_CIPHER);
            secretKey = new SecretKeySpec(passwordKey, ALGORITHM_CIPHER);
            ivParameterSpec = new IvParameterSpec(saltSecretKey);
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "No such algorithm " + ALGORITHM_CIPHER, e);
        } catch (NoSuchPaddingException e) {
            Log.e(TAG, "No such padding PKCS5", e);
        }              
    }

    public String encryptAsBase64(byte[] clearData) {
        byte[] encryptedData = encrypt(clearData);        
        return Base64.encodeToString(encryptedData,Base64.DEFAULT);
    }

    public byte[] encrypt(byte[] clearData) {
    byte[] encryptedData;
        try {
            aesCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
            encryptedData = aesCipher.doFinal(clearData);
        } catch (InvalidKeyException e) {
            Log.e(TAG, "Invalid key", e);
            return null;
        } catch (InvalidAlgorithmParameterException e) {
            Log.e(TAG, "Invalid algorithm " + ALGORITHM_CIPHER, e);
            return null;
        } catch (IllegalBlockSizeException e) {
            Log.e(TAG, "Illegal block size", e);
            return null;
        } catch (BadPaddingException e) {
            Log.e(TAG, "Bad padding", e);
            return null;
        }               
        return encryptedData;
    }

    private byte[] encodeDigest(String text) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance(ALGORITHM_DIGEST);            
            return digest.digest(text.getBytes());
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "No such algorithm " + ALGORITHM_DIGEST, e);
        }
        return null;
    }    
}

// C# Code

public class MyCrypto
{
private ICryptoTransform rijndaelDecryptor;
// Replace below with a 16-byte key, share between Java and C#
private static byte[] saltSecretKey = {0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 
0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f};

public MyCrypto(string passphrase)
{
byte[] passwordKey = encodeDigest(passphrase);
RijndaelManaged rijndael = new RijndaelManaged();
rijndaelDecryptor = rijndael.CreateDecryptor(passwordKey, rawSecretKey);
}

public string Decrypt(byte[] encryptedData)
{
byte[] newClearData = rijndaelDecryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.ASCII.GetString(newClearData);
}

public string DecryptFromBase64(string encryptedBase64)
{
return Decrypt(Convert.FromBase64String(encryptedBase64));
}

private byte[] encodeDigest(string text)
{
MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] data = Encoding.ASCII.GetBytes(text);
return x.ComputeHash(data);
}
}



Saturday, February 11, 2012

How to Encrypt / Decrypt Between Android and PHP?

How to use it in Java..
mcrypt = new MCrypt();
/* Encrypt */
String encrypted = MCrypt.bytesToHex( mcrypt.encrypt("Text to Encrypt") );
/* Decrypt */
String decrypted = new String( mcrypt.decrypt( encrypted ) );
How to use it in php...

$mcrypt = new MCrypt();
#Encrypt
$encrypted = $mcrypt->encrypt("Text to encrypt");
#Decrypt
$decrypted = $mcrypt->decrypt($encrypted);

/***********/

/**JAVA**/


import java.security.NoSuchAlgorithmException;


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


public class MCrypt {


private String iv = "fedcba9876543210";//Dummy iv (CHANGE IT!)
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;

private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!)

public MCrypt()
{
ivspec = new IvParameterSpec(iv.getBytes());


keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");

try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public byte[] encrypt(String text) throws Exception
{
if(text == null || text.length() == 0)
throw new Exception("Empty string");

byte[] encrypted = null;


try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);


encrypted = cipher.doFinal(padString(text).getBytes());
} catch (Exception e)
{
throw new Exception("[encrypt] " + e.getMessage());
}

return encrypted;
}

public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0)
throw new Exception("Empty string");

byte[] decrypted = null;


try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

decrypted = cipher.doFinal(hexToBytes(code));
} catch (Exception e)
{
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}




public static String bytesToHex(byte[] data)
{
if (data==null)
{
return null;
}

int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16)
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
else
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
return str;
}


public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}




private static String padString(String source)
{
 char paddingChar = ' ';
 int size = 16;
 int x = source.length() % size;
 int padLength = size - x;


 for (int i = 0; i < padLength; i++)
 {
 source += paddingChar;
 }


 return source;
}
}






====================================================


/**********/
/**PHP**/


<?php 


class MCrypt
{
private $iv = 'fedcba9876543210'; #Same as in JAVA
private $key = '0123456789abcdef'; #Same as in JAVA




function __construct()
{
}


function encrypt($str) {


 //$key = $this->hex2bin($key);    
 $iv = $this->iv;


 $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);


 mcrypt_generic_init($td, $this->key, $iv);
 $encrypted = mcrypt_generic($td, $str);


 mcrypt_generic_deinit($td);
 mcrypt_module_close($td);


 return bin2hex($encrypted);
}


function decrypt($code) {
 //$key = $this->hex2bin($key);
 $code = $this->hex2bin($code);
 $iv = $this->iv;


 $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);


 mcrypt_generic_init($td, $this->key, $iv);
 $decrypted = mdecrypt_generic($td, $code);


 mcrypt_generic_deinit($td);
 mcrypt_module_close($td);


 return utf8_encode(trim($decrypted));
}


protected function hex2bin($hexdata) {
 $bindata = '';


 for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
 }


 return $bindata;
}


}

Friday, February 10, 2012

How to encrypt and decrypt strings in android using AES?

Simple helper class to encrypt and decrypt strings using AES128. The result is Ascii-encoded (actually hex, no base64), so no byte[] has to be stored. A SEED value is used as a shared secret ("Master-Password"). Only with the same SEED the stored values can be decrypted. 

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Usage:
 * <pre>
 * String crypto = SimpleCrypto.encrypt(masterpassword, cleartext)
 * ...
 * String cleartext = SimpleCrypto.decrypt(masterpassword, crypto)
 * </pre>
 * @author ferenc.hechler
 */
public class SimpleCrypto {

 public static String encrypt(String seed, String cleartext) throws Exception {
  byte[] rawKey = getRawKey(seed.getBytes());
  byte[] result = encrypt(rawKey, cleartext.getBytes());
  return toHex(result);
 }
 
 public static String decrypt(String seed, String encrypted) throws Exception {
  byte[] rawKey = getRawKey(seed.getBytes());
  byte[] enc = toByte(encrypted);
  byte[] result = decrypt(rawKey, enc);
  return new String(result);
 }

 private static byte[] getRawKey(byte[] seed) throws Exception {
  KeyGenerator kgen = KeyGenerator.getInstance("AES");
  SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
  sr.setSeed(seed);
     kgen.init(128, sr); // 192 and 256 bits may not be available
     SecretKey skey = kgen.generateKey();
     byte[] raw = skey.getEncoded();
     return raw;
 }

 
 private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
     SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  Cipher cipher = Cipher.getInstance("AES");
     cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
     byte[] encrypted = cipher.doFinal(clear);
  return encrypted;
 }

 private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
     SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  Cipher cipher = Cipher.getInstance("AES");
     cipher.init(Cipher.DECRYPT_MODE, skeySpec);
     byte[] decrypted = cipher.doFinal(encrypted);
  return decrypted;
 }

 public static String toHex(String txt) {
  return toHex(txt.getBytes());
 }
 public static String fromHex(String hex) {
  return new String(toByte(hex));
 }
 
 public static byte[] toByte(String hexString) {
  int len = hexString.length()/2;
  byte[] result = new byte[len];
  for (int i = 0; i < len; i++)
   result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
  return result;
 }

 public static String toHex(byte[] buf) {
  if (buf == null)
   return "";
  StringBuffer result = new StringBuffer(2*buf.length);
  for (int i = 0; i < buf.length; i++) {
   appendHex(result, buf[i]);
  }
  return result.toString();
 }
 private final static String HEX = "0123456789ABCDEF";
 private static void appendHex(StringBuffer sb, byte b) {
  sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
 }
 
}