Java – AES Algoritması ile Encryption ve Decryption
Merhaba arkadaşlar
Bu yazımda sizlere AES algoritması kullarak nasıl Encryption işlemi yapabilirsiniz en basit haliyle anlatmak istiyorum. Eclipse i açtık yeni bir Java projesi olusturduk sonrasında 2 adet class’ı projemiz içersine ekledik isimleri TEST.java ve ENCRYPT.java.
Amaç aslında Encrypt.java class ını başka projelerde de kullanılacak şekilde dizayn etmek 😉
Encrypt class ı içersine aşağıdaki kodları ekleyeceksiniz. 🙂
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.*;
public class encrypt {
private static final String ALGO = "AES";
private static final byte[] keyValue = new byte[]
{ 'M', 'e', 'Z', 'O', 'b', 'l', 'o','g', 's', 'B', 'e','s', 't', 'K', 'e', 'y' };
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
return key;
}
}
Ardından test.java yani çalıştırılacak olan class ımız içersinde main metodu bulunduran class içersinede aşağıdaki kodları ekliyorsunuz. Encrypt classı içersinde oluşturduğumuz metotları çağırıyoruz.
public class test {
public static void main(String[] args) {
String password = "Hello Word İt's MEZO Blog";
String passwordEnc;
String passwordDec;
try {
passwordEnc = encrypt.encrypt(password);
passwordDec = encrypt.decrypt(encrypt.encrypt(password));
System.out.println("Plain Text : " + password);
System.out.println("Encrypted Text : " + passwordEnc);
System.out.println("Decrypted Text : " + passwordDec);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Ve işlemimiz bitti işte bu kadardı 🙂 artık Run As Java Application diyerek çalıştırıyor aşağıdaki çıktımızı alıyoruz.
Programımızın Çıktısı
Encrypt edilecek Text : Hello World It’s MEZO Blog
Encrypt edilmiş Text : 2loMo4Zhrtsbqg/4NOk1MpYp1uVbXkDwUNZKnons30o=
Decrypt edilmiş Text : Hello World It’s MEZO Blog
Umarım Yararlı Olmuştur
Bilgiyle Kalın
M.Zeki OSMANCIK
