IT/WEB

[JAVA] 파일 복호화(aes256)_참고용

오달달씨 2021. 4. 16. 16:30
728x90
반응형
public class FileAes256Util {
	
    private static String KEY = "9003e5a13d69a78c0d8210cb28b9d0d38e5445568899f637c24bc08241f98ded";
	private static String IV = "024e54561023da13118d16ac21119b8a";
    
	public static byte[] hexStringToByteArray(String s) {
		int len = s.length();
		byte[] data = new byte[len / 2];
		for (int i = 0; i < len; i += 2) {
			data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
		}
		return data;
	}

	public static String aes256Decode(String downFileName, String localPath, String FileName) {
	   
      byte[] _key = hexStringToByteArray(KEY);
      byte[] _iv = hexStringToByteArray(IV);

      InputStream input = null;
      OutputStream output = null;

      SecretKeySpec keyspc = new SecretKeySpec(_key, "AES");
      IvParameterSpec ivSpec = new IvParameterSpec(_iv);

      try {

         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
         cipher.init(Cipher.DECRYPT_MODE, keyspc, ivSpec);

         input = new BufferedInputStream(new FileInputStream(localPath + "/" + downFileName));
         downFileName = downFileName.substring(0, downFileName.length()-4);
         output = new BufferedOutputStream(new FileOutputStream(localPath + File.separator + downFileName)); 
         
         byte[] buffer = new byte[1024];
         int read = -1;
         while ((read = input.read(buffer)) != -1) {
            output.write(cipher.update(buffer, 0, read));
         }
         output.write(cipher.doFinal());
         
         logUtil.printMsg(0, "AES-256 DECODING SUCCESS, FILE_NAME="+downFileName);

      } catch (IOException e) {
          return "FAIL";
      } catch (Exception e) {
          return "FAIL";
      } finally {
         if (output != null) {
            try {
               output.close();
            } catch (IOException ie) {
              return "FAIL";
            }
         }
         if (input != null) {
            try {
               input.close();
            } catch (IOException ie) {
              return "FAIL";
            }
         }
      }
      return downFileName;
   }
}
728x90
반응형