2013년 3월 20일 수요일

암호화/복호화


import java.security.*;
import javax.crypto.*;
public class SimpleExample {
    public static void main(String [] args) throws Exception {
        if( args.length != 1) {
            System.out.println("Usage : java SimpleExample text ");
            System.exit(1);
        }
        String text = args[0];
        System.out.println("Generating a DESded (TripleDES) key...");
        // Triple DES 생성
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
        keyGenerator.init(168); // 키의 크기를 168비트로 초기화
        Key key = keyGenerator.generateKey();
        System.out.println("키생성이 완료되었음");
        System.out.println("key=" + key);
        // Cipher를 생성, 사용할 키로 초기화
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte [] plainText = text.getBytes("UTF8");
        System.out.println("Plain Text : ");
        for (int i = 0; i < plainText.length ; i++) {
            System.out.print(plainText[i] + " ");
        }
        // 암호화 시작
        byte [] cipherText = cipher.doFinal(plainText);
        // 암호문서 출력
        System.out.println("\nCipher Text : ");
        for (int i = 0; i < cipherText.length ; i++) {
            System.out.print(cipherText[i] + " ");
        }
        //복호화 모드로서 다시 초기화
        cipher.init(Cipher.DECRYPT_MODE, key);
        //복호화 수행
        byte [] decryptedText = cipher.doFinal(cipherText);
        String output =  new String(decryptedText, "UTF8");
        System.out.println("\nDecrypted Text : " + output);
    }
}

댓글 없음: