..:Welcome to My Blog:..

Clock

Entri Populer

Powered By Blogger

Total Tayangan Halaman

Pages

Enkripsi & Dkripsi

Enkripsi adalah sebuah proses yang melakukan perubahan sebuah kode dari yang bisa
dimengerti (Plaintext) menjadi sebuah kode yang tidak bisa dimengerti (Ciphertext). Sedangkan
proses kebalikannya untuk mengubah ciphertext mejadi plaintext disebut dekripsi. Sebuah system pengkodean menggunakan suatu table atau kamus yang telah didefinisikan untuk mengganti kata atau informasi atau yang merupakan bagian dari informasi yang dikirim. Secara umum operasi enkripsi dan dekripsi secara matematis dapat digambarkan sebagai berikut:
EK (M) = C {proses enkripsi}
DK (C) = M {proses dekripsi}
Pada proses enkripsi pesan M dengan suatu kunci K disandikan menjadi pesan C. pada proses
dekripsi pesan C dengan kunci K disandikan menjadi pesan semula yaitu M. misalnya S (sender)
mengirim sebuah pesan ke R (receiver) dengan media transmisi T. Di luar, ada O yang
menginginkan pesan tersebut dan mencoba untuk mengakses secara ilegal pesan tersebut. O disebut interceptor atau intruder. Setelah S mengirim pesan ke R melalui media T, O bisa mengakses pesan tersebut dengan cara-cara sebagai berikut:
a. Menggangu pesan, dengan mencegah pesan sampai ke R.
b. Mencegat pesan, dengan cara mengetahui isi pesan tersebut.
c. Mengubah pesan dari bentuk aslinya dengan cara apapun.
d. Memalsukan pesan yang terlihat asli, jadi seolah-olah sebuah pesan dikirim oleh S.
Untuk melindungi pesan asli dari gangguan seperti ini dan menjamin keamanan dan kerahasiaan data maka mulai dikenal sistem kriptografi untuk melindungi data, yaitu dengan mengenkripsi pesan dan untuk bisa membaca pesan kembali seperti aslinya pesan harus didekripsi. Kriptografi merupakan cara yang paling praktis untuk melindungi data yang ditransmisikan melalui sarana telekomunikasi.
A. Enkripsi Konvensional.
Proses enkripsi ini dapat digambarkan sebagai berikut :
Plain teks -> Algoritma Enkripsi -> Cipher teks ->Algoritma Dekripsi -> Plain teks


Informasi asal yang dapat di mengerti di simbolkan oleh Plain teks, yang kemudian oleh algoritma Enkripsi diterjemahkan menjadi informasi yang tidak dapat untuk dimengerti yang disimbolkan dengan cipher teks. Proses enkripsi terdiri dari dua yaitu algoritma dan kunci. Kunci biasanya merupakan suatu string bit yang pendek yang mengontrol algoritma. Algoritma enkripsi akan menghasilkan hasil yang berbeda tergantung pada kunci yang digunakan. Mengubah kunci dari enkripsi akan mengubah output dari algortima enkripsi.
Sekali cipher teks telah dihasilkan, kemudian ditransmisikan. Pada bagian penerima selanjutnya cipher teks yang diterima diubah kembali ke plain teks dengan algoritma dan dan kunci yang sama.
Keamanan dari enkripsi konvensional bergantung pada beberapa faktor. Pertama algoritma enkripsi harus cukup kuat sehingga menjadikan sangat sulit untuk mendekripsi cipher teks dengan dasar cipher teks tersebut. Lebih jauh dari itu keamanan dari algoritma enkripsi konvensional bergantung pada kerahasian dari kuncinya bukan algoritmanya. Yaitu dengan asumsi bahwa adalah sangat tidak praktis untuk mendekripsikan informasi dengan dasar cipher teks dan pengetahuan tentang algoritma diskripsi / enkripsi. Atau dengan kata lain, kita tidak perlu menjaga kerahasiaan dari algoritma tetapi cukup dengan kerahasiaan kuncinya.
Manfaat dari konvensional enkripsi algoritma adalah kemudahan dalam penggunaan secara luas. Dengan kenyataan bahwa algoritma ini tidak perlu dijaga kerahasiaannya dengan maksud bahwa pembuat dapat dan mampu membuat suatu implementasi dalam bentuk chip dengan harga yang murah. Chips ini dapat tersedia secara luas dan disediakan pula untuk beberapa jenis produk. dengan penggunaan dari enkripsi konvensional, prinsip keamanan adalah menjadi menjaga keamanan dari kunci.
Model enkripsi yang digunakan secara luas adalah model yang didasarkan pada data encrytion standard (DES), yang diambil oleh Biro standart nasional US pada tahun 1977. Untuk DES data di enkripsi dalam 64 bit block dengan menggunakan 56 bit kunci. Dengan menggunakan kunci ini, 64 data input diubah dengan suatu urutan dari metode menjadi 64 bit output. Proses yang yang sama dengan kunci yang sama digunakan untuk mengubah kembali enkripsi.
B. Enkripsi Public-Key
Salah satu yang menjadi kesulitan utama dari enkripsi konvensional adalah perlunya untuk mendistribusikan kunci yang digunakan dalam keadaan aman. Sebuah cara yang tepat telah diketemukan untuk mengatasi kelemahan ini dengan suatu model enkripsi yang secara mengejutkan tidak memerlukan sebuah kunci untuk didistribusikan. metode ini dikenal dengan nama enkripsi public-key dan pertama kali diperkenalkan pada tahun 1976.
Plain teks -> Algoritma Enkripsi -> Cipher teks -> Algoritma Dekrispsi -> Plain teks

Algoritma tersebut seperti yang digambarkan pada gambar diatas. Untuk enkripsi konvensional, kunci yang digunakan pada prosen enkripsi dan dekripsi adalah sama. Tetapi ini bukanlah kondisi sesungguhnya yang diperlukan. Namun adalah dimungkinkan untuk membangun suatu algoritma yang menggunakan satu kunci untuk enkripsi dan pasangannya, kunci yang berbeda, untuk dekripsi. Lebih jauh lagi adalah mungkin untuk menciptakan suatu algoritma yang mana pengetahuan tentang algoritma enkripsi ditambah kunci enkripsi tidak cukup untuk menentukan kunci dekrispi. Sehingga teknik berikut ini akan dapat dilakukan :
  1. Masing – masing dari sistem dalam network akan menciptakan sepasang kunci yang digunakan untuk enkripsi dan dekripsi dari informasi yang diterima.
  2. Masing – masing dari sistem akan menerbitkan kunci enkripsinya ( public key ) dengan memasang dalam register umum atau file, sedang pasangannya tetap dijaga sebagai kunci pribadi ( private key ).
  3. Jika A ingin mengisim pesan kepada B, maka A akan mengenkripsi pesannya dengan kunci publik dari B.
  4. Ketika B menerima pesan dari A maka B akan menggunakan kunci privatenya untuk mendeskripsi pesan dari A.
Seperti yang kita lihat, public-key memecahkan masalah pendistribusian karena tidak diperlukan suatu kunci untuk didistribusikan. Semua partisipan mempunyai akses ke kunci publik ( public key ) dan kunci pribadi dihasilkan secara lokal oleh setiap partisipan sehingga tidak perlu untuk didistribusikan. Selama sistem mengontrol masing – masing private key dengan baik maka komunikasi menjadi komunikasi yang aman. Setiap sistem mengubah private key pasangannya public key akan menggantikan public key yang lama. Yang menjadi kelemahan dari metode enkripsi publik key adalah jika dibandingkan dengan metode enkripsi konvensional algoritma enkripsi ini mempunyai algoritma yang lebih komplek. Sehingga untuk perbandingan ukuran dan harga dari hardware, metode publik key akan menghasilkan performance yang lebih rendah. Tabel berikut ini akan memperlihatkan berbagai aspek penting dari enkripsi konvensional dan public key.
Enkripsi Konvensional
Yang dibutuhkan untuk bekerja :
  1. Algoritma yang sama dengan kunci yang sama dapat digunakan untuk proses dekripsi – enkripsi.
  2. Pengirim dan penerima harus membagi algoritma dan kunci yang sama.
Yang dibutuhkan untuk keamanan :
  1. Kunci harus dirahasiakan.
  2. Adalah tidak mungkin atau sangat tidak praktis untuk menerjemahkan informasi yang telah dienkripsi.
  3. Pengetahuan tentang algoritma dan sample dari kata yang terenkripsi tidak mencukupi untu menentukan kunc.
Enkripsi Public Key
Yang dibutuhkan untuk bekerja :
  1. Algoritma yang digunakan untuk enkripsi dan dekripsi dengan sepasang kunci, satu untuk enkripsi satu untuk dekripsi.
  2. Pengirim dan penerima harus mempunyai sepasang kunci yang cocok.
Yang dibutuhkan untuk keamanan :
  1. Salah satu dari kunci harus dirahasiakan.
  2. Adalah tidak mungkin atau sangat tidak praktis untuk menerjemahkan informasi yang telah dienkripsi.
  3. Pengetahuan tentang algoritma dan sample dari kata yang terenkripsi tidak mencukupi untu menentukan kunci.

Files

The File classes
The File class manipulates disk files and is used to construct FileInputStreams and
FileOutputStreams. Some constructors for the File I/O classes take as a parameter an
object of the File type. When we construct a File object, it represents that file on disk.
When we call its methods, we manipulate the underlying disk file.
The methods for File objects are:
* Constructors
* Test methods
* Action methods
* List methods
Constructors
Constructors allow Java code to specify the initial values of an object. So when you're using
constructors, initialization becomes part of the object creation step. Constructors for the
File class are:
* File(String filename)
* File(String pathname, String filename)
* File(File directory, String filename)
Test Methods
Public methods in the File class perform tests on the specified file. For example:
* The exists() method asks if the file actually exists.
* The canRead() method asks if the file is readable.
* The canWrite() method asks if the file can be written to.
* The isFile() method asks if it is a file (as opposed to a directory).
* The isDirectory() method asks if it is a directory.
These methods are all of the boolean type, so they return a true or false.
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Action methods
Public instance methods in the File class perform actions on the specified file. Let's take a
look at them:
* The renameTo() method renames a file or directory.
* The delete() method deletes a file or directory.
* The mkdir() method creates a directory specified by a File object.
* The mkdirs() method creates all the directories and necessary parents in a File
specification.
The return type of all these methods is boolean to indicate whether the action was
successful.
List methods
The list() method returns the names of all entries in a directory that are not rejected by an
optional FilenameFilter. The list() method returns null if the File is a normal file, or
returns the names in the directory. The list() method can take a FilenameFilter filter
and return names in a directory satisfying the filter.
FilenameFilter interface
The FilenameFilter interface is used to filter filenames. You simply create a class that
implements the FilenameFilter. There are no standard FilenameFilter classes
implemented by the Java language, but objects that implement this interface are used by the
FileDialog class and the list() method in the File class.
The implemented accept() method determines if the filename in a directory should be
included in a file list. It is passed the directory and a file name. The method returns true if the
name should be included in the list.
File class: Example code
This example shows a file being tested for existence and a listing of the C:\Windows
directory. The listing is performed for all files and then for files matching a filter.
Here is the example code:
import java.io.*;
import java.util.*;
class FileClassExample
{
public static void main(String argv[])
{
File a_file = new File("test.txt");
if (a_file.canRead())
System.out.println("Can read file");
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

if (a_file.isFile())
System.out.println("Is a file");
File a_directory = new File("C:backslash, backslashWindows");
// red font indicates that an actual backslash n (carriage return character)
// should be inserted in the code.
if (a_directory.isDirectory())
{
System.out.println("Is a directory");
String names[] = a_directory.list();
for (int i = 0; i < names.length; i++)
{
System.out.println("Filename is " + names[i]);
}
}
System.out.println("Parent is " + a_directory.getParent());
if (a_directory.isDirectory())
{
String names[] = a_directory.list(new MyFilter());
for (int i = 0; i < names.length; i++)
{
System.out.println("Filename is " + names[i]);
}
}
}
}
class MyFilter implements FilenameFilter
{
public boolean accept(File directory, String name)
{
if (name.charAt(0) = = 'A' || name.charAt(0) = = 'a')
return true;
}
}
FileInputStream and FileOutputStream
You can open a file for input or output.
FileInputStream reads from a disk file. You can pass that constructor either the name of
a file or a File object that represents the file. The FileInputStream object is a source of
data.
FileOutputStream writes to a disk file. You can pass it a File object or a name. The
FileOutputStream object is a sink for data.
For FileInputStream and FileOutputStream, you read and write bytes of data.
File: Example code
This example works like the previous examples, except the output is to a file. We open the
file and write the data as bytes. After closing the file, we open it for reading, read all the bytes
in the file, and print them as a string.
Here is the example code:
import java.io.*;
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

import java.util.*;
class FileExample
{
static BufferedReader system_in = new BufferedReader
(new InputStreamReader(System.in));
public static void main(String argv[])
{
// Create it
{
try
{
FileOutputStream fos = new FileOutputStream("file.dat");
// Read in three hotels
for (int i = 0; i < 3; i++)
{
Hotel a_hotel = new Hotel();
a_hotel.input(system_in);
a_hotel.write_to_fos(fos);
}
fos.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
// Now display it
{
byte [] buffer = null;
File a_file = new File("file.dat");
System.out.println("Length is " + a_file.length());
System.out.println(" Can read " + a_file.canRead());
try
{
FileInputStream fis = new FileInputStream(a_file);
int length = (int) a_file.length();
buffer = new byte[length];
fis.read(buffer);
fis.close();
}
catch(IOException e)
{
System.out.println(e);
}
String s = new String(buffer);
System.out.println("Buffer is " + s);
}
}
}
class Hotel
{
private String name;
private int rooms;
private String location;
boolean input(BufferedReader in)
{
try
{
System.out.println("Name: ");
name = in.readLine();
System.out.println("Rooms: ");
String temp = in.readLine();
rooms = to_int(temp);
System.out.println("Location: ");
location = in.readLine();
}
catch(IOException e)
{
System.err.println(e);
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
Introduction to Java I/O Page 22
return false;
}
return true;
}
boolean write_to_fos(FileOutputStream fos)
{
try
{
fos.write(name.getBytes());
Integer i = new Integer(rooms);
fos.write(i.toString().getBytes());
fos.write(location.getBytes());
fos.write(' ');
}
catch (IOException e)
{
System.err.println(e);
return false;
}
return true;
}
void debug_print()
{
System.out.println("Name :" + name +
": Rooms : " + rooms + ": at :" + location+ ":");
}
static int to_int(String value)
{
int i = 0;
try
{
i = Integer.parseInt(value);
}
catch(NumberFormatException e)
{}
return i;
}
}
FileReader and FileWriter
FileReader is a convenience subclass of InputStreamReader. FileReader is useful
when you want to read characters from a file. The constructors of FileReader assume a
default character encoding and buffer size. FileReader constructors use the functionality of
InputStreamReader to convert bytes using the local encoding to the Unicode characters
used by Java code.
If you want to read Unicode characters from a file that uses encoding other than the default,
you must construct your own InputStreamReader on FileInputStream.
FileWriter is a convenience subclass of OutputStreamWriter for writing character
files. Constructors for FileWriter also assume default encoding and buffer size. If you
want to use encoding other than the default, you must create your own
OutputStreamWriter on FileOutputStream.

Sources and sinks

Byte arrays
Let's head toward byte array territory. Are bytes going to come from a byte array? When an
object of a ByteArrayInputStream is created, it is passed an array. You can then read
bytes from that array as an InputStream.
ByteArrayOutputStream writes to a byte array. Bytes that are written to the output
stream are added to an internal array. You may be wondering how you get to the byte array.
The toByteArray() method returns to you the byte array at any point in time. Also, a
toString() method is available, which returns the byte array as a String. Therefore, the
byte array can be either a source or a sink.
Pipes in Java code
What is a pipe? A pipe is a means of communication between two threads of a Java
program. One thread writes to a piped output stream and another thread reads from a piped
input stream, which is connected to the piped output stream.
A pipe between two threads works like a pipe works between two processes in UNIX and
MS-DOS. In those operating systems, the output from one process can be piped to the input
of another process. For example, in MS-DOS, the command "dir | more" pipes the output of
the "dir" command to the input of the "more" program.
Pipe: Example code
Although pipes are usually used with threads, this example simply writes data to a pipe and
then reads it back later.
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

First, a PipedReader is constructed, then a PipedWriter that writes to that
PipedReader. The attributes are written to the pipe as strings with a vertical bar as a
delimiter and a new-line character placed at the end. The entire contents of the
PipedReader are read as a String and displayed.
We'll show later, in Tokenizing on page 51, how to use a StringTokenizer to break up a
string that is delimited into individual values.

Here is the example code:
import java.io.*;
import java.util.*;
class PipedExample
{
static BufferedReader system_in = new BufferedReader
(new InputStreamReader(System.in));
public static void main(String argv[])
{
PipedReader pr = new PipedReader();
PipedWriter pw = null;
try {
pw = new PipedWriter(pr);
}
catch (IOException e)
{
System.err.println(e);
}
// Create it {
// Read in three hotels
for (int i = 0; i < 3; i++)
{
Hotel a_hotel = new Hotel();
a_hotel.input(system_in);
a_hotel.write_to_pw(pw);
}
}
// Print it
{
char [] buffer = new char[1000];
int length = 0;
try
{
length = pr.read(buffer);
}
catch (IOException e)
{
System.err.println(e);
}
String output =new String(buffer, 0, length);
System.out.println("String is ");
System.out.println(output);
}
}
}
class Hotel
{
private String name;
private int rooms;
private String location;
boolean input(BufferedReader in)
{
try
{
System.out.println("Name: ");
name = in.readLine();
System.out.println("Rooms: ");
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
Introduction to Java I/O Page 14
String temp = in.readLine();
rooms = to_int(temp);
System.out.println("Location: ");
location = in.readLine();
}
catch(IOException e)
{
System.err.println(e);
return false;
}
return true;
}
boolean write_to_pw(PipedWriter pw)
{
try
{
pw.write(name);
Integer i = new Integer(rooms);
pw.write(i.toString());
pw.write(location);
pw.write('backslash n');
// red font indicates that an actual backslash n (carriage return character)
// should be inserted in the code.
}
catch(IOException e)
{
System.err.println(e);
return false;
}
return true;
}
void debug_print()
{
System.out.println("Name :" + name +
": Rooms : " + rooms + ": at :" + location+ ":");
}
static int to_int(String value)
{
int i = 0;
try
{
i = Integer.parseInt(value);
}
catch(NumberFormatException e)
{}
return i;
}
}
Sequences
SequenceInputStream combines input streams and reads each input stream until the end.
You can use SequenceInputStream to read two or three streams as if they were one
stream. You can concatenate streams from various sources, such as two or more files. To
construct a SequenceInputStream, you can specify either two streams or an
Enumeration, which represents a set of input streams. A program such as "cat" in UNIX
would use something like this.
SequenceInputStream reads from the first underlying input stream that it is given. When
the first one is exhausted, it opens the next input stream and reads that one. When that one
is exhausted, it reads the next, and so on.
The user does not know when the input is transferred from one stream to the next stream;
another byte is simply read. When all the input streams have been read, an EOF is received
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

from the entire input stream.
Char arrays
Now let's explore Readers and Writers. The read and write methods input and output a
character. Similar to ByteArrayOutputStream, a CharArrayWriter writes characters to
a char array. As a character is written to a CharArrayWriter object, it's added to an array
of characters whose size is automatically incremented.
At any point in time, we can get the character array that we have filled up. The
toCharArray() method returns an array of characters. A CharArrayReader uses a
character array as a source. Typically, the array is one that has been created with a
CharArrayWriter object. With an alternative constructor, you can specify not only the
array, but where to start in the array (an offset) and how many bytes to read (a length) before
you return an EOF character.
String: Example code
StringWriter works like CharArrayWriter. An internal StringBuffer object is the
destination of the characters written. Methods associated with the class are getBuffer(),
which returns the StringBuffer itself, and toString(), which returns the current value
of the string.
StringReader works like CharArrayReader. It uses a String object as the source of
the characters it returns. When a StringReader is created, you must specify the String
that it is read from.
In this example, instead of writing to a pipe, we are going to write to a String. A
StringWriter object is constructed. After the output is complete, we obtain the contents
with toString() and print it out. This works like the previous example with PipedReader
and PipedWriter, except a String is used to contain the data.
Here is the example code:
import java.io.*;
import java.util.*;
class StringExample
{
static BufferedReader system_in = new BufferedReader
(new InputStreamReader (System.in));
public static void main(String argv[])
{
StringWriter sw = new StringWriter();
// Create it
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

{
// Read in three hotels
for (int i = 0; i < 3; i++)
{
Hotel a_hotel = new Hotel();
a_hotel.input(system_in);
a_hotel.write_to_string(sw);
}
}
// Print it
{
String output = sw.toString();
System.out.println("String is ");
System.out.println(output);
}
}
}
class Hotel
{
private String name;
private int rooms;
private String location;
boolean input(BufferedReader in)
{
try
{
System.out.println("Name: ");
name = in.readLine();
System.out.println("Rooms: ");
String temp = in.readLine();
rooms = to_int(temp);
System.out.println("Location: ");
location = in.readLine();
}
catch(IOException e)
{
System.err.println(e);
return false;
}
return true;
}
boolean write_to_string(StringWriter sw)
{
sw.write(name);
Integer i = new Integer(rooms);
sw.write(i.toString());
sw.write(location);
sw.write('backslash n');
// red font indicates that an actual backslash n (carriage return character)
// should be inserted in the code.
return true;
}
void debug_print()
{
System.out.println("Name :" + na
": Rooms : " + rooms + ": at :" + location+ ":");
}
static int to_int(String value)
{
int i = 0;
try
{
i = Integer.parseInt(value);
}
catch(NumberFormatException e)
{}
return i;
}
}
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

InputStreamReader
InputStreamReader reads bytes from an InputStream and converts them to characters.
An InputStreamReader uses the default character encoding for the bytes, which is usually
ASCII. If the bytes that are being read are ASCII bytes, only a byte at a time is used to form a
character.
If the bytes are not ASCII, such as Chinese or another language, you want conversion to
Unicode as well. Specific encoding of the byte stream is necessary, and the
InputStreamReader converts it to Unicode. With an alternate constructor, you can specify
the encoding of the bytes on the InputStream.
OutputStreamReader
OutputStreamWriter is similar to InputStreamReader. The output characters, which
are in Unicode, are converted to the underlying format of the machine using an
OutputStreamWriter. The converted characters are written to an OutputStream. The
underlying default format is typically ASCII. However, you can state a specific encoding
scheme with an alternate constructor.
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

java.io class overview

Input stream classes
In the InputStream class, bytes can be read from three different sources:
* An array of bytes
* A file
* A pipe
Sources, such as ByteArrayInputStream and FilterInputStream, subclass the
InputStream class. The subclasses under InflatorInputStream and
FilterInputStream are listed in the figure below.
InputStream methods
Various methods are included in the InputStream class.
* abstract int read() reads a single byte, an array, or a subarray of bytes. It returns
the bytes read, the number of bytes read, or -1 if end-of-file has been reached.
* read(), which takes the byte array, reads an array or a subarray of bytes and returns a
-1 if the end-of-file has been reached.
* skip(), which takes long, skips a specified number of bytes of input and returns the
number of bytes actually skipped.
* available() returns the number of bytes that can be read without blocking. Both the
input and output can block threads until the byte is read or written.
* close() closes the input stream to free up system resources.
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

InputStream marking
Some, but not all, InputStreams support marking. Marking allows you to go back to a
marked place in the stream like a bookmark for future reference. Remember, not all
InputStreams support marking. To test if the stream supports the mark() and reset()
methods, use the boolean markSupported() method.
The mark() method, which takes an integer read_limit, marks the current position in
the input stream so that reset() can return to that position as long as no more than the
specified number of bytes have been read between the mark() and reset().
OutputStream classes
Bytes can be written to three different types of sinks:
* An array of bytes
* A file
* A pipe
The following figure shows OutputStream classes.
Let's look at some examples of OutputStream classes. Before sending an OutputStream
to its ultimate destination, you can filter it. For example, the BufferedOutputStream is a
subclass of the FilterOutputStream that stores values to be written in a buffer and writes
them out only when the buffer fills up.
CheckedOutputStream and DigestOutputStream are part of the
FilterOutputStream class. They calculate checksums or message digests on the output.
DeflatorOutputStream writes to an OutputStream and creates a zip file. This class
does compression on the fly.
The PrintStream class is also a subclass of FilterOutputStream, which implements a
number of methods for displaying textual representation of Java primitive types. For
example:
* println(long)
* println(int)
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

* println(float)
* println(char)
DataOutputStream implements the DataOutput interface. DataOutput defines the
methods required for streams that can write Java primitive data types in a
machine-independent binary format.
OutputStream methods
The OutputStream class provides several methods:
* The abstract void write() method takes an integer byte and writes a single byte.
* The void write() method takes a byte array and writes an array or subarray of
bytes.
* The void flush() method forces any buffered output to be written.
* The void close() method closes the stream and frees up system resources.
It is important to close your output files because sometimes the buffers do not get completely
flushed and, as a consequence, are not complete.
DataInput and DataOutput
The DataInput and DataOutput classes define the methods required for streams that can
read Java primitive data types in a machine-independent binary format. They are
implemented by RandomAccessFile.
The ObjectInput interface extends the DataInput interface and adds methods for
deserializing objects and reading bytes and arrays of bytes. You can learn more about
serialization in Object serialization on page 46.
The ObjectOutputStream class creates a stream of objects that can be deserialized by
the ObjectInputStream class.
The ObjectOutput interface extends the DataOutput interface and adds methods for
serializing objects and writing bytes and arrays of bytes.
ObjectOutputStream is used to serialize objects, arrays, and other values to a stream.

read() APIs:
int read()
read (char[] buffer,
int offset, int length)
What are Readers?
Readers are character-based input streams that
read Unicode characters.
* read() reads a single character and returns
a character read as an integer in the range
from 0 to 65535 or a -1 if the end of the
stream is reached.
* abstract read() reads characters into a
portion of an array (starting at offset up to
length number of characters) and returns the
number of characters read or -1 if the end of
the stream is reached.
Character input streams
Let's take a look at the different character input streams in the java.io package.
* Strings
* Character arrays
* Pipes
InputStreamReader is a character input stream that uses a byte input stream as its data
source and converts it into Unicode characters.
LineNumberReader, a subclass of BufferedReader, is a character input stream that
keeps track of the number of lines of text that have been read from it.
PushbackReader, a subclass of FilterReader, is a character input stream that uses
another input stream as its input source and adds the ability to push characters back onto the
stream.
write() APIs:
void write(int character)
void write(char[] buffer,
int offset, int length)
What are Writers?
Writers are character-based output streams that
write character bytes and turn Unicode into bytes.
The base class includes these methods:
* The void write() method, which takes a
character and writes single character in 16
low-order bits
* The abstract void write() method,
which takes a character array and writes a
portion of an array of characters
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
Introduction to Java I/O Page 11
Character output streams
Let's take a look at the different character output streams in the java.io package. There
are several branches of this inheritance tree you can explore. Like Readers, any of the
branches are available. Sinks for Writer output can be:
* Strings
* CharArray
* Pipes
OutputStreamWriter uses a byte output stream as the destination for its data.
BufferedWriter applies buffering to a character output stream, thus improving output
efficiency by combining many small write requests into a single large request.
FilterWriter is an abstract class that acts as a superclass for character output streams.
The streams filter the data written to them before writing it to some other character output
stream.
PrintWriter is a character output stream that implements print() and println()
methods that output textual representations of primitive values and objects.

Enkripsi Dan Dekripsi

Kriptografi, secara umum adalah ilmu dan seni untuk menjaga kerahasiaan berita [bruce Schneier - Applied Cryptography]. Selain pengertian tersebut terdapat pula pengertian ilmu yang mempelajari teknik-teknik matematika yang berhubungan dengan aspek keamanan informasi seperti kerahasiaan data, keabsahan data, integritas data, serta autentikasi data [A. Menezes, P. van Oorschot and S. Vanstone - Handbook of Applied Cryptography]. Tidak semua aspek keamanan informasi ditangani oleh kriptografi.

Ada empat tujuan mendasar dari ilmu kriptografi ini yang juga merupakan aspek keamanan informasi yaitu :
1. Kerahasiaan, adalah layanan yang digunakan untuk menjaga isi dari informasi dari siapapun kecuali yang memiliki otoritas atau kunci rahasia untuk membuka/mengupas informasi yang telah disandi.
2. Integritas data, adalah berhubungan dengan penjagaan dari perubahan data secara tidak sah. Untuk menjaga integritas data, sistem harus memiliki kemampuan untuk mendeteksi manipulasi data oleh pihak-pihak yang tidak berhak, antara lain penyisipan, penghapusan, dan pensubsitusian data lain kedalam data yang sebenarnya.
3. Autentikasi, adalah berhubungan dengan identifikasi/pengenalan, baik secara kesatuan sistem maupun informasi itu sendiri. Dua pihak yang saling berkomunikasi harus saling memperkenalkan diri. Informasi yang dikirimkan melalui kanal harus diautentikasi keaslian, isi datanya, waktu pengiriman, dan lain-lain.
4. Non-repudiasi., atau nirpenyangkalan adalah usaha untuk mencegah terjadinya penyangkalan terhadap pengiriman/terciptanya suatu informasi oleh yang mengirimkan/membuat.

Enkripsi Untuk Keamanan Data Pada Jaringan
Salah satu hal yang penting dalam komunikasi menggunakan computer untuk menjamin kerahasian data adalah enkripsi. Enkripsi dalah sebuah proses yang melakukan perubahan sebuah kode dari yang bisa dimengerti menjadi sebuah kode yang tidak bisa dimengerti (tidak terbaca). Enkripsi dapat diartikan sebagai kode atau chiper. Sebuah sistem pengkodean menggunakan suatu table atau kamus yang telah didefinisikan untuk mengganti kata dari informasi atau yang merupakan bagian dari informasi yang dikirim. Sebuah chiper menggunakan suatu algoritma yang dapat mengkodekan semua aliran data (stream) bit dari sebuah pesan menjadi cryptogram yang tidak dimengerti (unitelligible). Karena teknik cipher merupakan suatu sistem yang telah siap untuk di automasi, maka teknik ini digunakan dalam sistem keamanan komputer dan network.


Dalam setiap transaksi di internet , idealnya, setiap data yang ditransmisikan harusnya terjamin :
  • Integritas data
Jaminan integritas data sangat penting, sehingga data yang di kirimkan akan sama persis dengan data yang diterima, tanpa mengalami perubahan apapun pada selama ditransmisikan.

  • Kerahasiaan data
Jaminan kerahasiaan data juga penting karena dengan demikian tidak ada pihak lain yang bisa membaca data yang ada selama data tersebut ditransmisikan.

  • Otentikasi akse data
Mekanisme otentikasi akses data menjamin bahwa data ditransmisikan oleh pihak yang benar dengan tujuan transimisi yang benar pula.

Teknik kriptografi data untuk enkripsi ada dua macam yaitu:
1. Kriptografi simetrik, Dengan model kriptografi ini, data di enkripsi dan didekripsi dengan kunci rahasia yang sama.
2. Kriptografi asimetrik, Dengan model kriptografi ini, data dienkripsi dan didekripsi dengan kunci rahasia yang berbeda.pasangan kunci untuk enkripsi dan dekripsi dikenal dengan private key dan public key.

Stream I/O Introduction

Basic input and output classes
The java.io package contains a fairly large number of classes that deal with Java input
and output. Most of the classes consist of:
* Byte streams that are subclasses of InputStream or OutputStream
* Character streams that are subclasses of Reader and Writer
The Reader and Writer classes read and write 16-bit Unicode characters. InputStream
reads 8-bit bytes, while OutputStream writes 8-bit bytes. As their class name suggests,
ObjectInputStream and ObjectOutputStream transmit entire objects.
ObjectInputStream reads objects; ObjectOutputStream writes objects.
Unicode is an international standard character encoding that is capable of representing most
of the world's written languages. In Unicode, two bytes make a character.
Using the 16-bit Unicode character streams makes it easier to internationalize your code. As
a result, the software is not dependent on one single encoding.
What to use
There are a number of different questions to consider when dealing with the java.io
package:
* What is your format: text or binary?
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

* Do you want random access capability?
* Are you dealing with objects or non-objects?
* What are your sources and sinks for data?
* Do you need to use filtering?
Text or binary
What's your format for storing or transmitting data? Will you be using text or binary data?
* If you use binary data, such as integers or doubles, then use the InputStream and
OutputStream classes.
* If you are using text data, then the Reader and Writer classes are right.
Random access
Do you want random access to records? Random access allows you to go anywhere within a
file and be able to treat the file as if it were a collection of records.
The RandomAccessFile class permits random access. The data is stored in binary format.
Using random access files improves performance and efficiency.
Object or non-object
Are you inputting or outputting the attributes of an object? If the data itself is an object, then
use the ObjectInputStream and ObjectOutputStream classes.
Sources and sinks for data
What is the source of your data? What will be consuming your output data, that is, acting as
a sink? You can input or output your data in a number of ways: sockets, files, strings, and
arrays of characters.
Any of these can be a source for an InputStream or Reader or a sink for an
OutputStream or Writer.
Filtering
Do you need filtering for your data? There are a couple ways to filter data.
Buffering is one filtering method. Instead of going back to the operating system for each byte,
you can use an object to provide a buffer.
Checksumming is another filtering method. As you are reading or writing a stream, you might
want to compute a checksum on it. A checksum is a value you can use later on to make sure
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
the stream was transmitted properly.
Storing data records
A data record is a collection of more than one element, such as names or addresses. There
are three ways to store data records:
* Use delimited records, such as a mail-merge style record, to store values. On output,
data values are converted to strings separated by delimiters such as the tab character,
and ending with a new-line character. To read the data back into Java code, the entire
line is read and then broken up using the StringTokenizer class.
* Use fixed size records to store data records. Use the RandomAccessFile class to
store one or more records. Use the seek() method to find a particular record. If you
choose this option to store data records, you must ensure strings are set to a fixed
maximum size.
* Alternatively, you can use variable length records if you use an auxiliary file to store the
lengths of each record. Use object streams to store data records. If object streams are
used, no skipping around is permitted, and all objects are written to a file in a sequential
manner.
Creating streams: Example code
Here is an example of how to create a stream that reads and writes characters using a
TCP/IP socket as the sink and source. The classes themselves are explained later.
First, we create a TCP/IP socket object that is connected to www.ibm.com and port 80. This
is the Web server port. The method getInputStream() in the Socket class returns an
InputStream, which represents byte-by-byte reading of the socket. The InputStream is
used to create an InputStreamReader, which transforms the bytes read from the socket
into characters. A BufferedReader class is created, which reads from the
InputStreamReader and buffers the characters into its own internal buffer. The object
named in then reads characters from that buffer, but the ultimate source of the characters is
the Web server at www.ibm.com.
On the other hand, the getOutputStream() method of the Socket class returns a
reference to an OutputStream, which writes a byte at a time. The PrinterWriter
constructor uses that OutputStream as the sink for the characters it writes out. When a
character is written to the object named out, it is ultimately sent to the Web server at
www.ibm.com.
This example treats the data stream as character data:
Socket a_socket = new Socket(www.ibm.com, 80);
InputStreamReader isr = new InputStreamReader(
a_socket.getInputStream());
BufferedReader in = new BufferedReader (isr);
PrinterWriter out = new PrinterWriter(
a_socket.getOutputStream());
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

A second way to use streams is to use them to transmit binary data. We create a TCP/IP
socket object that is connected to www.ibm.com and port 100. We construct a
DataInputStream using the InputStream returned by getInputStream() and a
DataOutputStream using the OutputStream returned by getOutputStream(). We can
send and receive integers or doubles or other binary data over these two streams.
This example treats the data stream as binary data:
Socket socket_data = new Socket(www.ibm.com, 100);
DataInputStream in_data = new DataInputStream(
socket_data.getInputStream());
DataOutputStream out_data = new DataOutputStream(
socket_data.getOutputStream());
Exceptions
Almost every input or output method throws an exception. Therefore, any time you do I/O,
you need to catch exceptions. There is a large hierarchy of I/O exceptions derived from
IOException. Typically you can just catch IOException, which catches all the derived
exceptions. However, some exceptions thrown by I/O methods are not in the IOException
hierarchy. One such exception is the java.util.zip.DataFormatException. This
exception is thrown when invalid or corrupt data is found while data being read from a zip file
is being uncompressed. java.util.zip.DataFormatException has to be caught
explicitly because it is not in the IOException hierarchy.
Remember, exceptions in Java code are thrown when something unexpected happens.
List of exceptions
This figure shows a list of exceptions:
Let's look at a few examples:
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

* EOFException signals when you reach an end-of-file unexpectedly.
* UnknownHostException signals that you are trying to connect to a remote host that
does not exist.
* ZipException signals that an error has occurred in reading or writing a zip file.
Typically, an IOException is caught in the try block, and the value of the toString()
method of the Object class in the IOException is printed out as a minimum. You should
handle the exception in a manner appropriate to the application.
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
Introduction

Event Handling GUI Pada Java

Dalam event handling pada Java ada empat bagian penting yang harus diketahui:
  1. Event Object merupakan object yang mendiskripsikan sebuah event yang di-trigger oleh event source.
  2. Event Handler merupakan method yang menerima event object dan melakukan respond yang sesuai dengan event object tersebut.
  3. Event Listener merupakan interface yang akan meng-handle event yang terjadi. setiap type event mempunyai interface yang bersesuaian. Listener tersebut harus diimplementasikan oleh class yang akan meng-handle event
  4. Event Source merupakan pembangkit / trigger sebuah event objects
setiap event object mempunyai  type event yang berbdea beda. sehingga kita harus menentukan type event sebelum menentukan jenis interface listener. karena setiap type event mempunyai jenis interface listener yang bersesuaian.

berikut ini type type event yang ada di Java :
  1. ActionEvent
  2. ItemEvent
  3. WindowEvent
  4. ContainerEvent
  5. ComponentEvent
  6. FocusEvent
  7. TextEvent
  8. KeyEvent
  9. MouseEvent
  10. AdjustmentEvent
Berikut ini Interface Listener
  1. ActionListener
  2. ItemListener
  3. WindowListener
  4. ContainerListener
  5. ComponentListener
  6. FocusListener
  7. TextListener
  8. KeyListener
  9. MouseListener
  10. MouseMotionListener
  11. AdjustmentListener
Berdasarkan tulisan diatas, setiap type event mempunyai satu jenis interface listener kecuali MouseEvent yang mempunyai dua jenis interface listener. dan setiap interface mempunyai method abstract yang harus di override class yang meng-impletasikan interface. event listener dan event handler terdapat pada package java.awt.event
Bagaimana event handling dalam Java? ada tiga langkah penting dalam event handling
  1. Deklarasikan class yang akan meng-handle event yang terjadi dan tuliskan code yang menyatakan class tersebut meng-implement interface listener
  2. Event source mendaftarkan sebuah listener melalui method add<type>Listener
  3. Kode yang mengimplementasikan method pada interface listener pada class yang akan meng-handle event. [ Override ]

Macam-Macam GUI Toolkit Pada Java

  • AWT (Abstract Window Toolkit) – SUN Microsystem -> Oracle Product
AWT (Abstract Window Toolkit) ini adalah GUI Toolkit pertama pada bahasa pemrograman Java, sayang-nya AWT ini sangat-sangat kekurangan komponen yang biasa digunakan untuk membangun sebuah aplikasi desktop secara lengkap . Terlepas dari kurang-nya komponen GUI yang terdapat pada AWT (Abstract Window Toolkit), aplikasi yang dibangun menggunakan AWT (Abstract Window Toolkit) akan tampak seperti aplikasi native. Maksudnya yaitu, jika aplikasi yang dibangun menggunakan AWT (Abstract Window Toolkit) ini dijalankan pada Sistem Operasi Windows. Maka aplikasi ini akan terlihat seperti aplikasi Windows pada umum-nya, dan begitu juga jika dijalankan pada Sistem Operasi Mac ataupun GNU/Linux. Kenapa ini bisa terjadi, karena AWT (Abstract Window Toolkit) ini benar-benar memanggil native subrutin untuk menggambar setiap komponen-nya ke layar.

  •  Java Swing – SUN Microsystem -> Oracle
Dibandingkan dengan pendahulu-nya yaitu AWT (Abstract Window Toolkit), Swing mempunyai lebih banyak komponen pendukung untuk membangun sebuah aplikasi yang lengkap untuk keperluan desktop. Selain didukung dengan banyak-nya komponen, Swing ini benar-benar murni 100 % ditulis dengan bahasa pemrograman Java tanpa adanya sebuah wrapper untuk memanggil rutin-rutin native code via JNI (Java Native Interface). Seluruh komponen yang terdapat pada Swing, semuanya murni digambar sendiri menggunakan API (Application Programming Interface) 2D untuk memanggil rutin-rutin dasar penggambaran komponen-nya. Nah dengan model seperti ini, memungkinkan sekali aplikasi yang dibangun menggunakan Swing tampak sama persis di berbagai macam Sistem Operasi.
Selain itu, Swing juga mempunyai kemampuan untuk berganti-ganti tampilan menggunakan LAF (Look And Feel) atau themes . Sayang-nya, jika kita menginginkan tampilan GUI yang native (tampilan-nya sama seperti aplikasi-aplikasi lain pada sistem operasi target) Swing seperti-nya masih terasa kurang smooth terutama dukungan pada font rendering-nya .

  • SWT (Standart Widget Tookit) – IBM Product -> Eclipse Foundation
SWT (Standart Widget Toolkit) ini adalah sebuah GUI Toolkit yang dikeluaran oleh IBM sebagai alternatif dari AWT/Java Swing milik SUN Microsystem, yang membedakan antara SWT (Standart Widget Toolkit) dan AWT/Java Swing adalah SWT ini benar-benar mengakses native GUI library yang terdapat pada Sistem Operasi melalui JNI (Java Native Interface). Dengan model seperti ini, memungkinkan tampilan aplikasi yang dibangun menggunakan GUI Toolkit SWT menjadi sama persis dengan aplikasi native lain-nya. Kekurangan dari model pemanggilan native GUI library seperti ini adalah kita harus menyediakan library untuk tiap-tiap Sistem Operasi target aplikasi kita.

  • QtJambi – Trolltech -> Nokia Product -> Stopped and Taken By Community
Jika teman-teman ingin membangun aplikasi yang tampilan-nya tampak seperti aplikasi yang terdapat pada KDE tapi masih ingin menggunakan bahasa java sebagai dasar-nya, maka QtJambi adalah pilihan yang tepat untuk teman-teman. Karena QtJambi ini merupakan binding Qt Framework dengan bahasa Java, tetapi sayang-nya proyek QtJambi sudah tidak disupport oleh Nokia dan secara resmi telah ditutup . Untung-nya, awal tahun ini ada beberapa developer yang peduli dengan kelangsungan proyek ini dan akhir-nya membuat sebuah komunitas untuk melanjutkan pengembangan proyek QtJambi.

Pengikut