반응형

 

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;

public class decPw {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
        // 16자리 임의 값 입력 필수
		String AESKey = "aaaaaaaaaaaaaaaa";
		String pwd;
		
		System.out.println("Enter the encryption value :");
        // 사용자에게 값 입력 받아서 복호화
		pwd = sc.next();
		
		String decPwd = decrypt(pwd, AESKey);
		
		System.out.println("----decode result----\n" + decPwd);

	}
    
    private static String encrypt(String input, String key) {
		byte[] crypted = null;
		SecretKeySpec sks = new SecretKeySpec(key.getBytes(), "AES");
		
		try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, sks);
			crypted = cipher.doFinal(input.getBytes());
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		BASE64Encoder encoder = new BASE64Encoder();
		String str = encoder.encode(crypted);
		return new String(str);
	}
	
	private static String decrypt(String input, String key) {
		byte[] output = null;
		
		BASE64Decoder decoder = new BASE64Decoder();
		
		SecretKeySpec sks = new SecretKeySpec(key.getBytes(), "AES");
		
		Cipher cipher;
		try {
			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, sks);
			output = cipher.doFinal(decoder.decodeBuffer(input));
			
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		return new String (output);
	}


}
반응형
복사했습니다!