"This is not about miles, every mountain has its own beauty to climb"

Encryption Dan Decryption AES dengan Menggunakan javax.crypto

Berikut salah satu implementasi enkripsi dan dekripsi AES pada Java menggunakan javax.crypto. Ini adalah program untuk melakukan manage terhadap login user yang ditampung dalam suatu file namun yang disimpan dalam sudah dienkripsi menggunakan AES.

Enkripsi.java

package javauselibrary;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Enkripsi {
private Cipher aes;
private SecretKey aeskey;
public Enkripsi(String key) {
try {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
//Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
aes = Cipher.getInstance(“AES”);
aeskey = new SecretKeySpec(key.getBytes(), “AES”);
} catch(Exception e) {
e.printStackTrace();
}
}
public String encrypt(String str) throws Exception {
aes.init(Cipher.ENCRYPT_MODE, aeskey);
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes(“UTF8″);
// Encrypt
byte[] enc = aes.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str) throws Exception {
aes.init(Cipher.DECRYPT_MODE, aeskey);
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = aes.doFinal(dec);
// Decode using utf-8
return new String(utf8,”UTF8”);
}

}

Penjelasan :

Method Enkripsi digunakan untuk menggenerate aeskey dari string key yang dimasukkan dalam parameter method. Method decrypt adalah method yang dapat mendekrip dari parameter string chipertext (string hasil enkripsi) dan menghasilkan return string plaintext (string awal sebelum dienkripsi). Method encrypt adalah method yang dapat mengenkrip dari parameter string plaintext dan menghasilkan return string chipertext.

UserManager.java

//untuk melakukan manage user

package javauselibrary;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author rangga
*/
public class UserManager {

/**
* Lokasi file username dan passwordnya
*/
String _databaseFileLocation;

/**
* Constructor
*/
public UserManager(){

}

/**
* Menambah user ke dalam database
*
* @param username : plain text
* @param password : plain text
*/
public void addUser(String username, String password) throws IOException, Exception {
try {

//Enkripsi AES
// Generate a temporary key. In practice,you would save this key.

// Create encrypter/decrypter class
Enkripsi encrypter = new Enkripsi(“hemmelighemmelig”);
// Encrypt
String encrypted_user = encrypter.encrypt(username);
String encrypted_pass = encrypter.encrypt(password);
// Decrypt
//String decrypted = encrypter.decrypt(encrypted);
// TODO :
// – enkripsi username dan password
// – cari di database (file) apakah username sudah ada
// – jika ada, ganti password nya
// – jika tidak, tambah
Properties p = new Properties();

p.load(new FileInputStream(“username.prop”));

String cek = p.getProperty(encrypted_user, “null”);
if (cek.equals(“null”)) {
p.setProperty(encrypted_user, encrypted_pass);
p.store(new FileOutputStream(“username.prop”), “ini adalah komentar”);
} else {
if (cek.equals(encrypted_pass)) {
System.out.println(“Username dan Password sudah ada dalam database!”);
} else {
p.setProperty(encrypted_user, encrypted_pass);
p.store(new FileOutputStream(“username.prop”), “ini adalah komentar”);
}
}
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(UserManager.class.getName()).log(Level.SEVERE, null, ex);
}

}

/**
* Proses login
*
* @param username – plain text
* @param password – plain text
* @return true jika usernama dan password cocok, false jika sebaliknya
*/
public boolean login(String username, String password) throws IOException, Exception {

// TODO :

// Create encrypter/decrypter class
Enkripsi encrypter = new Enkripsi(“hemmelighemmelig”);
// Encrypt
String encrypted_user = encrypter.encrypt(username);
String encrypted_pass = encrypter.encrypt(password);
// Decrypt
//String decrypted = encrypter.decrypt(encrypted);

Properties p = new Properties();
FileInputStream BacaFile = new FileInputStream(“username.prop”);

p.load(BacaFile);
String cek_user = p.getProperty(encrypted_user, “null”);
//String cek_pass = p.getProperty(encrypted_pass, “null”);

System.out.println(“User :” + cek_user);
//System.out.println(“Pass :” + cek_pass);
// – cari di database
// – jika tidak, return false
if(cek_user.equals(“null”)){
return false;
}
// – jika ada , return true
else{
if(cek_user.equals(encrypted_pass)){
return true;
}else{
return false;
}

}
}

/**
* Set new password
*
* @param username
* @param oldPassword password lama
* @param newPassword password baru
* @return true jika bisa di set, false jika gagal
*/
public boolean setPassword( String username, String oldPassword, String newPassword ) throws IOException, Exception {

// NOTE :
// kl implementasi method login() dan addUser() sudah bener
// ini gk perlu diubah

// cek oldPassword nya bener apa nggak
// kl bener baru set
if( login(username, oldPassword) ) {
addUser(username, newPassword);
return true;
}
else
return false;

}
public boolean delUser(String username, String password) throws Exception{

// Create encrypter/decrypter class
Enkripsi encrypter = new Enkripsi(“hemmelighemmelig”);
// Encrypt
String encrypted_user = encrypter.encrypt(username);
String encrypted_pass = encrypter.encrypt(password);
// Decrypt
//String decrypted = encrypter.decrypt(encrypted);

Properties p = new Properties();
FileInputStream BacaFile = new FileInputStream(“username.prop”);

p.load(BacaFile);
String cek_user = p.getProperty(encrypted_user, “null”);
//String cek_pass = p.getProperty(encrypted_pass, “null”);

//System.out.println(“User :” + cek_user);
//System.out.println(“Pass :” + cek_pass);
// – cari di database
// – jika tidak, return false
if(cek_user.equals(“null”)){
return false;
}
// – jika ada , return true
else{
if(cek_user.equals(encrypted_pass)){
System.out.println(“User Dihapus :” + cek_user);
p.remove(encrypted_user);
p.store(new FileOutputStream(“username.prop”), “ini adalah komentar”);
return true;
}else{
return false;
}

}

}
}

Main.java

package javauselibrary;

import java.io.IOException;

/**
*
* @author rangga
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, Exception {
UserManager um = new UserManager();
um.addUser(“rangga”,”manis”); //menambah user
um.addUser(“Putri”, “Wawoet”);
um.addUser(“Buset”, “Bajol”);
boolean cek = um.delUser(“buset”, “Bajol”); //mendelete user
System.out.println(cek);

}

}

yang tersimpan dalam file username.prop telah terenkripsi dengan menggunakan AES

#ini adalah komentar
#Fri Apr 04 22:38:05 ICT 2008
eOl0SZSXYhOdlsJwwIXp7w\=\==izgzsLdAaOzH+jOB9XAdTQ\=\=
aJDo3hwyQ+Trpe96Dh6k6Q\=\==TpuT22ioB6Ahtj8/bsue2Q\=\=
zfCTQ6WQ9yz7qRZm0OweCw\=\==sEpsvYC3OJbD7xRP3dnbyQ\=\=

2 responses

  1. precious soul

    yg saya agak bingung,
    SecretKey aeskey = new SecretKeySpec(key.getBytes(), “AES”);
    itu maksudnya menggenerate key tu gmn ya? Soalnya saya pengennya key-ny ga berubah.. cuz walopun pake SecretKeySpec yg sama, pas men-generate secret key, berubah2 gt, so ciphertextnya jd brubah2 d..
    jd saya pengennya secret keynya itu langsung key.getBytes(), kira2 gmn carany y? Jadinya hasil ciphertextnya ga brubah-brubah.. Buat validasi apakah bener2 implement AES ato ga.
    Makasi…

    16 March 2009 at 4:41 am

  2. adlis

    c472553ca566ddeb8a2030611eaba3b66b8f1b9e
    kk mw tnya ini tipenya apa ya ? md5 gk bisa soalnya

    2 January 2011 at 7:26 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s