Algoritma Kriptografi AES menggunakan libary javax.crypto


Kali ini kita mencoba mengaplikasikan Algoritma Encryption Standart melalui pemograman sederhana java dengan menggunakan library java.crypto

Input data dan key yang kita gunakan adalah data berupa string. berikut script nya:

import java.io.IOException;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.Cipher;


public class kriptoaesckrip {
	static String IV = "AAAAAAAAAAAAAAAA";
	static String plaintext = "test text 123\0\0\0"; /*Note null padding*/
	static String encryptionKey = "0123456789abcdef";
	
	public static void main(String args[])throws IOException{
		try {
		      
		      System.out.println("==Java==");
		      System.out.println("plain:   " + plaintext);

		      byte[] cipher = encrypt(plaintext, encryptionKey);

		      System.out.print("cipher:  ");
		      for (int i=0; i<cipher.length; i++)
		        System.out.print(new Integer(cipher[i])+" ");
		      System.out.println("");

		      String decrypted = decrypt(cipher, encryptionKey);

		      System.out.println("decrypt: " + decrypted);

		    } catch (Exception e) {
		      e.printStackTrace();
		    } 
	}
	
	public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
	Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
	SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
	cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
	return cipher.doFinal(plainText.getBytes("UTF-8"));
	}

	public static String decrypt(byte[] cipherText, String encryptionKey) throws Exception{
	Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
	SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
	cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
	return new String(cipher.doFinal(cipherText),"UTF-8");

		  }
	
}


hasil yang akan didapatkan adalah sebagai berikut
plain: test text 123
cipher: 16 -124 41 -83 -16 -123 61 -64 -15 -74 87 28 63 30 64 78
decrypt: test text 123

Advertisements

Author: ridhobustami

orang ngak jelas

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