develog

AES 본문

Dev/Java

AES

냐옴 2013. 1. 27. 16:53

import java.math.BigInteger;


import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;



public class AES {

public static void main(String[] args) throws Exception {

AES main = new AES();

SecretKey key = main.generateSecretKey();

String message = "암호화 테스트";

System.out.println("암호전 : " + message);

String encrypted = main.encrypt(message, key);

System.out.println("암호화 : " + encrypted);

String decrypted = main.decrypt(encrypted, key);

System.out.println("복호화 : " + decrypted);

}

public SecretKey generateSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator.getInstance("AES");

keygen.init(128);

SecretKey skey = keygen.generateKey();

return skey;

}

public String encrypt(String message, SecretKey key) throws Exception {

SecretKeySpec skeySpec = new SecretKeySpec(key.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

byte[] encrypted = cipher.doFinal(message.getBytes());

return new BigInteger(encrypted).toString(16);

}

public String decrypt(String encrypted, SecretKey key) throws Exception {

SecretKeySpec skeySpec = new SecretKeySpec(key.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

byte[] decrypted = cipher.doFinal(new BigInteger(encrypted, 16).toByteArray());

return new String(decrypted);

}

}


'Dev > Java' 카테고리의 다른 글

variable arguments  (0) 2013.02.23
XML DOM  (0) 2013.01.27
poi 대용량 엑셀 write  (0) 2013.01.08
Quartz job fire manually  (0) 2012.12.18
Quartz - Defining a Job  (0) 2012.12.14
Comments