Tampilkan postingan dengan label Android. Tampilkan semua postingan
Tampilkan postingan dengan label Android. Tampilkan semua postingan

Senin, 05 November 2012

Simple Temperature Conversion Apps for Android (Aplikasi Konversi Suhu Sederhana untuk Android)

Ok, in this post, I'll post a simple apps for conversion of temperature. This apps for only Android phone. And this is the capture of the application.
In this apps, I use spinner to add dropdown box like in a website. Ok, to make this app, so these are the codes you need to write.

First of all is main activity layout, I named it activity_conversion.xml. It's look like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="14dp"
        android:text="@string/hello_world"
        tools:context=".ConversionActivity" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="16dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/spinner1"
        android:layout_below="@+id/spinner1"
        android:layout_marginTop="20dp"
        android:text="@string/hello2" />

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="22dp" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/spinner2"
        android:layout_below="@+id/spinner2"
        android:layout_marginTop="14dp"
        android:text="@string/insert_temp" />

    <EditText
        android:id="@+id/insert_editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="20dp"
        android:ems="10" />

    <Button
        android:id="@+id/convert_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/insert_editText"
        android:layout_below="@+id/insert_editText"
        android:text="@string/convert_button" />

    <EditText
        android:id="@+id/result_editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/convert_button"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/result_editText"
        android:layout_alignLeft="@+id/result_editText"
        android:layout_marginBottom="22dp"
        android:text="@string/result" />

</RelativeLayout>

And for the second is strings.xml. Here it's the code for strings.xml:
<resources>

    <string name="app_name">TempConversion</string>
    <string name="hello_world">Choose your temperature from</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_conversion">ConversionActivity</string>
    <string name="hello2">Conversion to</string>
    <string name="insert_temp">Insert your temperature</string>
    <string name="result">The result is</string>
    <string name="convert_button">Convert</string>
    <string-array name="nama_suhu">
        <item>Celcius</item>
        <item>Fahrenheit</item>
        <item>Kelvin</item>
        <item>Reamur</item>
    </string-array>
    <string-array name="nama_suhu2">
        <item>Celcius</item>
        <item>Fahrenheit</item>
        <item>Kelvin</item>
        <item>Reamur</item>
    </string-array>

</resources>

Next is the main activity, I named it with ConversionActivity.java. And the codes are:
package org.tempconversion;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class ConversionActivity extends Activity implements OnItemSelectedListener{

    //private String suhu1, suhu2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversion);
       
        final Spinner pilTemp1 = (Spinner)findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.nama_suhu, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        pilTemp1.setAdapter(adapter);
        final Spinner pilTemp2 = (Spinner)findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.nama_suhu2, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        pilTemp2.setAdapter(adapter2);
        final EditText inputTemp = (EditText)findViewById(R.id.insert_editText);
        final EditText resultTemp = (EditText)findViewById(R.id.result_editText);
        final Button convertButton = (Button)findViewById(R.id.convert_button);
       
        // event for button
        convertButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String suhu1 = pilTemp1.getSelectedItem().toString();
                String suhu2 = pilTemp2.getSelectedItem().toString();
                String strSuhu = inputTemp.getText().toString();
                String strSuhuAkhir = "";
                double suhuAwal = Double.parseDouble(strSuhu);
                double suhuResult = 0;
                // selection for converting suhu
                // start with Celcius first
                if(suhu1.equals("Celcius")) {
                    if(suhu2.equals("Fahrenheit")) {
                        suhuResult = (suhuAwal * 9 / 5) + 32;
                    } else if(suhu2.equals("Kelvin")) {
                        suhuResult = suhuAwal + 273;
                    } else if(suhu2.equals("Reamur")) {
                        suhuResult = suhuAwal * 4 / 5;
                    } else {
                        suhuResult = suhuAwal;
                    }
                } else if(suhu1.equals("Fahrenheit")) {
                    if(suhu2.equals("Celcius")) {
                        suhuResult = (suhuAwal - 32) * 5 / 9;
                    } else if(suhu2.equals("Kelvin")) {
                        suhuResult = (suhuAwal - 459) * 5 / 9;
                    } else if(suhu2.equals("Reamur")) {
                        suhuResult = (suhuAwal - 32) * 4 / 9;
                    } else {
                        suhuResult = suhuAwal;
                    }
                } else if(suhu1.equals("Kelvin")) {
                    if(suhu2.equals("Celcius")) {
                        suhuResult = suhuAwal - 273;
                    } else if(suhu2.equals("Fahrenheit")) {
                        suhuResult = suhuAwal * 9 / 5 - 459;
                    } else if(suhu2.equals("Reamur")) {
                        suhuResult = (suhuAwal - 273) * 4 / 5;
                    } else {
                        suhuResult = suhuAwal;
                    }
                } else if(suhu1.equals("Reamur")) {
                    if(suhu2.equals("Celcius")) {
                        suhuResult = suhuAwal * 5 / 4;
                    } else if(suhu2.equals("Kelvin")) {
                        suhuResult = suhuAwal * 5 / 4 + 273;
                    } else if(suhu2.equals("Fahrenheit")) {
                        suhuResult = suhuAwal * 9 / 4 + 32;
                    } else {
                        suhuResult = suhuAwal;
                    }
                }
                strSuhuAkhir = Double.toString(suhuResult);
                resultTemp.setText(strSuhuAkhir);
            }
        });
    }

    public void onItemSelected(AdapterView<?> parent, View view,
            int pos, long id) {
        // An item was selected. You can retrieve the selected item using
        // parent.getItemAtPosition(pos)
    }
   
    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
    }
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_conversion, menu);
        return true;
    }
}


Ok, that's all for sharing today. Happy coding and go open source.

Rabu, 17 Oktober 2012

Simple Encryption Aplications Using AES and MD5 ( Aplikasi Enkripsi Sederhana Menggunakan AES dan MD5 )

Ok, this time I'll share about simple apps for encryption using AES and MD5. I try to combine AES with MD5. The string will be encrypted with AES first, and then the cipher text will be encrypted again with MD5. So, this is the capture of the applications.
The first field is for key encryption, and the second field is for the teks to be encrypted.
To create this app, I use 3 classes. The first class is an activity called AesMd5.java, GenerateAes.java, Md5Baru.java.
For the source code  to create this simple apps I'll show below.
The first is
AesMd5.java

package org.aesmd5;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.*;
import android.widget.Button;
import android.widget.EditText;

public class AesMd5 extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aes_md5);
       
        final Button enkripButton = (Button)findViewById(R.id.enkrip_button);
        final EditText inputKunci = (EditText)findViewById(R.id.input_kunci);
        final EditText inputKata = (EditText)findViewById(R.id.input_kata);
        final EditText teksEnkrip = (EditText)findViewById(R.id.teks_enkrip);
        // handling for Encryption
        enkripButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String ambilKunci = inputKunci.getText().toString();
                String ambilKata = inputKata.getText().toString();
                String enKata = "";
                try {
                    enKata = GenerateAES.encrypt(ambilKunci, ambilKata);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //teksEnkrip.setText(enKata);
                teksEnkrip.setText(Md5Baru.MD5(enKata));
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_aes_md5, menu);
        return true;
    }
}


GenerateAes.java

package org.aesmd5;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.SecureRandom;

public class GenerateAES {
    //private Cipher cipher;
    //private SecretKeySpec sKey;
    public GenerateAES() {
    }
   
    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 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));
}
}


Md5Baru.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.aesmd5;
import java.security.*;
/**
 *
 * @author nang
 */
public class Md5Baru {

    public static String MD5(String text) {
        String md5 = "";
        byte test[] = text.getBytes();
        int panjang = 16;
        byte[] mesDig = new byte[panjang];
        try {
        MessageDigest mD = MessageDigest.getInstance("MD5");
        mD.reset();
        mD.update(text.getBytes(), 0, text.length());
        mD.digest(mesDig, 0, panjang);
        StringBuffer sB = new StringBuffer();
        for(int i=0; i<mesDig.length;i++) {
            //mesDig = mD.digest(test, 0, test.length);
            String hex = Integer.toHexString(0xFF & mesDig[i]);
            if(hex.length() == 1) {
                sB.append('0');
            }
            sB.append(hex);
        }
        md5 = sB.toString();
        } catch (Exception e){

        }
        return md5;
    }
}

And the last is activity_aes_md5.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:id="@+id/teks_kunci"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Masukkan kunci"
        />
    <EditText
        android:id="@+id/input_kunci"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/teks_kata"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Masukkan kata"
        />
    <EditText
        android:id="@+id/input_kata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/enkrip_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enkrip"
        />
    <EditText
        android:id="@+id/teks_enkrip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

Ok, that's all for today, happy coding, and go Open Source.

Selasa, 04 September 2012

Aplikasi Enkripsi dan Dekripsi Menggunakan AES di Android

Kriptograpi pada salah satu buku dituliskan sebagai ilmu yang merahasiakan sebuah rahasia. Salah satu metode yang dapat digunakan untuk merahasiakan sebuah rahasia adalah enkripsi.
Untuk kali ini akan saya sharing sebuah aplikasi enkripsi dan dekripsi menggunakan Algoritma AES yang berjalan di Android. Untuk library yang saya gunakan pada aplikasi ini adalah JCE (Java Cryptography Extension). Tampilan dari aplikasi ini adalah sebagai berikut:

Untuk mulai membangun aplikasi ini, terlebih dahulu dibuat layout dari aplikasi. kode untuk menampilkan tampilan seperti di atas adalah sebagai berikut (ditulis di dalam main.xml yang berada di dalam direktory res/layout) :
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
   >  
 <TextView  
      android:id="@+id/teks_kunci"  
      android:layout_width="wrap_content"  
      android:layout_height="wrap_content"  
      android:text="Masukkan kunci"   
      />  
 <EditText  
      android:id="@+id/input_kunci"  
      android:layout_width="fill_parent"  
      android:layout_height="wrap_content"   
      />  
 <TextView  
      android:id="@+id/teks_kata"  
      android:layout_width="wrap_content"  
      android:layout_height="wrap_content"  
      android:text="Masukkan kata"   
      />  
 <EditText  
      android:id="@+id/input_kata"  
      android:layout_width="fill_parent"  
      android:layout_height="wrap_content"   
      />  
 <Button   
      android:id="@+id/enkrip_button"  
      android:layout_width="wrap_content"  
      android:layout_height="wrap_content"  
      android:text="Enkrip"  
      />  
 <EditText  
      android:id="@+id/teks_enkrip"  
      android:layout_width="fill_parent"  
      android:layout_height="wrap_content"   
      />  
 <Button   
      android:id="@+id/dekrip_button"  
      android:layout_width="wrap_content"  
      android:layout_height="wrap_content"  
      android:text="Dekrip"  
      />  
 <EditText  
      android:id="@+id/teks_dekrip"  
      android:layout_width="fill_parent"  
      android:layout_height="wrap_content"   
      />  
 </LinearLayout>  




Selanjutnya adalah Activity utama dari aplikasi. Untuk aplikasi ini saya beri nama AESAndroidActivity dan kelas activitynya adalah AESAndroidActivity.java. Isi dari kelas AESAndroidActivity.java adalah sebagai berikut:


package org.aes;

import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
import android.view.View.*;

public class AESAndroidActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // set Instance
        final Button enkripButton = (Button)findViewById(R.id.enkrip_button);
        final Button dekripButton = (Button)findViewById(R.id.dekrip_button);
        final EditText inputKunci = (EditText)findViewById(R.id.input_kunci);
        final EditText inputKata = (EditText)findViewById(R.id.input_kata);
        final EditText teksEnkrip = (EditText)findViewById(R.id.teks_enkrip);
        final EditText teksDekrip = (EditText)findViewById(R.id.teks_dekrip);
        // handling for enkripButton
        enkripButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
        String ambilKunci = inputKunci.getText().toString();
        String ambilKata = inputKata.getText().toString();
        String enKata = "";
        try {
        enKata = GenerateAES.encrypt(ambilKunci, ambilKata);
        } catch (Exception e) {}
        teksEnkrip.setText(enKata);
        }
        });
        // handling for dekripButton
        dekripButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
        String ambilKunci = inputKunci.getText().toString();
        String ambilKata = teksEnkrip.getText().toString();
        String deKata = "";
        if(!ambilKata.equals(null)) {
            try {
            deKata = GenerateAES.decrypt(ambilKunci, ambilKata);
            } catch(Exception e) {
           
            }
            teksDekrip.setText(deKata);
        }
        }
        });
    }
}



Sedangkan kelas untuk menghasilkan algoritma AES pada aplikasi ini saya beri nama GenerateAES.java. Isi dari GenerateAES.java adalah sebagai berikut:


package org.aes;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.SecureRandom;

public class GenerateAES {
//private Cipher cipher;
//private SecretKeySpec sKey;
public GenerateAES() {
}

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 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));
}
}



Jika sudah jadi semua, tahap selanjutnya adalah melakukan kompilasi dan menjalankan aplikasi.
Happy coding. Salam open source.

Sabtu, 20 Agustus 2011

A little Documentation from My Experience Developing Android on Devkit8000 (part 1)

This is my little documentation from my experience developing android in devkit8000. Actually, I focuss on developing application for Android with Android SDK and Eclipse in Ubuntu 10.04.
So, I just need an Eclipse IDE, JDK 5 or 6, and android SDK, yup, that's all tools for developing Android in my case. Ok lets start, for the first time I'll install JDK 6 in my PC. These are the steps:
1. Open Terminal
2. Edit /etc/apt/sources.list with your favorite editor. In example:
$ sudo gedit /etc/apt/sources.list
And then delete the '#' in front of the line below:
deb http://archive.canonical.com/ubuntu lucid partner
deb-src http://archive.canonical.com/ubuntu lucid partner
3. Update repository
$ sudo apt-get update
4. Installing sun java
$ sudo apt-get install sun-java6-jdk
5. For testing your java installation you can run this command:
$ java -version

This is the end of part 1, and for the next part I'll write how to install Android SDK and make emulator for Android.