package seed.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.apache.log4j.Logger; /*import org.hyperic.sigar.CpuPerc; import org.hyperic.sigar.Mem; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException;*/ import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; public class SeedUtils { private static Logger log = Logger.getLogger(SeedUtils.class); private static MessageDigest md; static { try{ md = MessageDigest.getInstance("MD5"); }catch(Exception e){ md = null; } } private static byte[] md5(String source) { byte[] bytes = source.getBytes(); byte[] digest = md.digest(bytes); return digest; } public static String getSeedMD5Code(String str){ String MD5 = ""; try{ MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for(int i = 0 ; i < byteData.length ; i++){ sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1)); } MD5 = sb.toString(); }catch(NoSuchAlgorithmException e){ log.error("SeedUtils getSeedMD5Code Error"); MD5 = ""; } return MD5; } public static String getSeedSHA256Code(String str){ String SHA256 = ""; try{ MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(str.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for(int i = 0 ; i < byteData.length ; i++){ sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1)); } SHA256 = sb.toString(); }catch(NoSuchAlgorithmException e){ log.error("SeedUtils getSeedSHA256Code Error"); SHA256 = ""; } return SHA256; } public static String getSeedEncrypt(String input, String key){ byte[] ivbytes = "SeedSecretMd5ASE".getBytes(); IvParameterSpec ips = new IvParameterSpec(ivbytes); byte[] keybytes = md5(key); byte[] crypted = null; try{ SecretKeySpec skey = new SecretKeySpec(keybytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skey, ips); byte[] ptext = input.getBytes(); crypted = cipher.doFinal(ptext); }catch(NoSuchPaddingException e){ log.error("SeedUtils getSeedEncrypt NoSuchPaddingException"); }catch(NoSuchAlgorithmException e){ log.error("SeedUtils getSeedEncrypt NoSuchAlgorithmException"); }catch(InvalidKeyException e){ log.error("SeedUtils getSeedEncrypt InvalidKeyException"); }catch(InvalidAlgorithmParameterException e){ log.error("SeedUtils getSeedEncrypt InvalidAlgorithmParameterException"); }catch(IllegalBlockSizeException e){ log.error("SeedUtils getSeedEncrypt IllegalBlockSizeException"); }catch(BadPaddingException e){ log.error("SeedUtils getSeedEncrypt BadPaddingException"); } return new String(Hex.encodeHexString(crypted)); } public static String getSeedDecrypt(String input, String key){ IvParameterSpec ips = new IvParameterSpec("SeedSecretMd5ASE".getBytes()); byte[] keybytes = md5(key); byte[] output = null; try{ SecretKeySpec skey = new SecretKeySpec(keybytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skey, ips); output = cipher.doFinal(Hex.decodeHex(input.toCharArray())); }catch(NoSuchPaddingException e){ log.error("SeedUtils getSeedDecrypt NoSuchPaddingException"); }catch(NoSuchAlgorithmException e){ log.error("SeedUtils getSeedDecrypt NoSuchAlgorithmException"); }catch(InvalidKeyException e){ log.error("SeedUtils getSeedDecrypt InvalidKeyException"); }catch(InvalidAlgorithmParameterException e){ log.error("SeedUtils getSeedDecrypt InvalidAlgorithmParameterException"); }catch(IllegalBlockSizeException e){ log.error("SeedUtils getSeedDecrypt IllegalBlockSizeException"); }catch(BadPaddingException e){ log.error("SeedUtils getSeedDecrypt BadPaddingException"); }catch(DecoderException e){ log.error("SeedUtils getSeedDecrypt DecoderException"); } return new String(output); } public static String getSeedKisaEncrypt(String input){ String output = ""; try{ // 암복호화에 사용할 키 배열생성 int[] seedKeyByte = SeedKISA.getSeedRoundKey("SeedSecretKISARoundKey"); output = SeedKISA.getSeedEncrypt(input, seedKeyByte); }catch (Exception e) { log.error("SeedUtils getSeedKisaEncrypt Exception"); } return output; } public static String getSeedKisaDecrypt(String input){ String output = ""; try{ // 암복호화에 사용할 키 배열생성 int[] seedKeyByte = SeedKISA.getSeedRoundKey("SeedSecretKISARoundKey"); output = SeedKISA.getSeedDecrypt(input, seedKeyByte); }catch (Exception e) { log.error("SeedUtils getSeedKisaDecrypt Exception"); } return output; } /** * 전달 받은 경로의 폴더를 생성하는 메소드 mkdirs를 호출함 * -> 생성후 해당 폴더에 대한 권한 설정을 실행 * 생성된 폴더 및 파일 객체를 위의 메소드로 권한 수정 작업 진행 * 요거 하면 계정에 따라서 권한이 없어서 문제 발생 될수 있음 * Was=서버파일관리 권한이 완전 동일 해야함 * @param String dirPath 폴더 경로 */ /*public static void setSeedMkDirs(String dirPath){ File file = new File(dirPath); if (file.exists() || file.isDirectory()){ return; } if(!file.exists()){ file.mkdirs(); } }*/ public static void setSeedMkDirs(String dirPath) { File file = new File(dirPath); if (!file.exists() && !file.isDirectory()) { if (!file.exists()) { file.mkdirs(); } } } public static void setSeedFileCopy(String inFileName, String outFileName){ FileInputStream fis = null; FileOutputStream fos = null; try{ fis = new FileInputStream(inFileName); fos = new FileOutputStream(outFileName); byte[] buffer = new byte[(int)1024]; int i = 0; if (fis != null && fos != null) { while ((i = fis.read(buffer)) != -1) { fos.write(buffer, 0, i); } } fis.close(); fos.close(); }catch (FileNotFoundException e){ log.error(e); }catch (IOException e){ log.error(e); }catch (Exception e){ log.error(e); }finally{ if(fis!=null){try{fis.close();}catch(IOException e){log.error("CHECK ERROR:",e);}} if(fos!=null){try{fos.close();}catch(IOException e){log.error("CHECK ERROR:",e);}} } } public static void setSeedMoveFile(String dirPath, String destPath){ File orgFile = new File(dirPath); File destFile = new File(destPath); if(orgFile != null && orgFile.exists()){ orgFile.renameTo(destFile); } } public synchronized static void setSeedDeleteFile(String dirPath){ File file = new File(dirPath); if(file != null && file.exists()){ file.delete(); } } public synchronized static void setSeedDeleteFiles(String dirPath, String noFoloder) { File file = new File(dirPath); if (!file.exists() || !file.isDirectory()){ return; } String[] fnameList = file.list(); if(fnameList != null && fnameList.length > 0){ int fCnt = fnameList.length; String childPath = ""; for(int i = 0; i < fCnt; i++) { childPath = dirPath+"/"+fnameList[i]; File f = new File(childPath); if(noFoloder != null && !noFoloder.equals("")){ if(f.getName().equals(noFoloder)){ continue; } } if(f != null && !f.isDirectory()) { f.delete(); //파일이면 바로 삭제 }else { setSeedDeleteFiles(childPath, noFoloder); } } } File f = new File(dirPath); f.delete(); } public static void setSeedCopyFiles(File sourcelocation , File targetdirectory, String[] noCopyFolders, String[] noCopyFiles) { //디렉토리인 경우 if (sourcelocation.isDirectory()) { boolean chkNoFolder = false; for(int i=0; i -1){ chkNoFolder = true; break; } } if(!chkNoFolder){ //복사될 Directory가 없으면 만듭니다. if (!targetdirectory.exists()) { targetdirectory.mkdir(); } String[] children = sourcelocation.list(); if(children != null && children.length > 0){ for (int i=0; i 0){ for(int i=0; i -1){ chkNoFile = true; break; } } } if(!chkNoFile){ //파일인 경우 InputStream in = null; OutputStream out = null; try{ in = new FileInputStream(sourcelocation); out = new FileOutputStream(targetdirectory); //Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); }catch (IOException e){ log.error("IOException Error"); }finally{ if (in != null) { try{ in.close(); }catch (IOException e){ log.error("IOException Error"); } } if (out != null) { try{ out.close(); }catch (IOException e){ log.error("IOException Error"); } } } } } } public static ArrayList> getSeedDirFiles(String dirPath, String dirType) { ArrayList> arrayList = new ArrayList>(); File file = new File(dirPath); if (!file.exists() || !file.isDirectory()){ return null; } String[] fnameList = file.list(); int fCnt = 0; if(fnameList != null && fnameList.length > 0){ fCnt = fnameList.length; } String childPath = ""; for(int i = 0; i < fCnt; i++) { childPath = dirPath+"/"+fnameList[i]; File f = new File(childPath); if(f != null){ Map dirMap = new HashMap(); if(dirType.equals("D") && f.isDirectory()){ dirMap.put("dirName", f.getName()); arrayList.add(dirMap); }else if(dirType.equals("F") && !f.isDirectory()){ dirMap.put("fileName", f.getName()); dirMap.put("fileSize", f.length()); dirMap.put("fileSubType", f.getName().substring(f.getName().lastIndexOf(".")+1)); arrayList.add(dirMap); } } } return arrayList; } public static String getStandardPBEStringDecrypt(String strEncrypt){ String strDecrypt = strEncrypt.substring(4, strEncrypt.length()-1); StandardPBEStringEncryptor pbeEnc = new StandardPBEStringEncryptor(); pbeEnc.setPassword("web"); // PBE 값(XML PASSWORD설정) return pbeEnc.decrypt(strDecrypt); } public static String setReplaceNull(Object strOriginal){ if(strOriginal == null || strOriginal.equals("")){ strOriginal = ""; } // //주민번호 형태 인 경우 해당 *로 치환 // strOriginal = strOriginal.toString().replaceAll("\\d{6}(|\\p{Z}|\\p{Z}\\p{Z})\\-(|\\p{Z}|\\p{Z}\\p{Z})[1-4]\\d{6}", "******-*******"); // strOriginal = strOriginal.toString().replaceAll("\\d{6}(|\\p{Z}|\\p{Z}\\p{Z})\\~(|\\p{Z}|\\p{Z}\\p{Z})[1-4]\\d{6}", "******~*******"); // // //휴대폰 번호 인 경우 해당 *로 치환 // strOriginal = strOriginal.toString().replaceAll("^01(?:0|1|[6-9])(|\\p{Z}|\\p{Z}\\p{Z})-(|\\p{Z}|\\p{Z}\\p{Z})(?:\\d{3}|\\d{4}) - \\d{4}$", "***-****-****"); // strOriginal = strOriginal.toString().replaceAll("^01(?:0|1|[6-9])(|\\p{Z}|\\p{Z}\\p{Z})~(|\\p{Z}|\\p{Z}\\p{Z})(?:\\d{3}|\\d{4}) ~ \\d{4}$", "***~****~****"); // // //일반전화 번호, 팩스 번호 인 경우 해당 *로 치환 // strOriginal = strOriginal.toString().replaceAll("^\\d{2,3}(|\\p{Z}|\\p{Z}\\p{Z})-(|\\p{Z}|\\p{Z}\\p{Z})\\d{3,4}(|\\p{Z}|\\p{Z}\\p{Z})-(|\\p{Z}|\\p{Z}\\p{Z})\\d{4}$", "***-****-****"); // strOriginal = strOriginal.toString().replaceAll("^\\d{2,3}(|\\p{Z}|\\p{Z}\\p{Z})~(|\\p{Z}|\\p{Z}\\p{Z})\\d{3,4}(|\\p{Z}|\\p{Z}\\p{Z})~(|\\p{Z}|\\p{Z}\\p{Z})\\d{4}$", "***~****~****"); // // //카드번호 인 경우 해당 *로 치환 // strOriginal = strOriginal.toString().replaceAll("\\d{4}(|\\p{Z}|\\p{Z}\\p{Z})-(|\\p{Z}|\\p{Z}\\p{Z})\\d{4}(|\\p{Z}|\\p{Z}\\p{Z})-(|\\p{Z}|\\p{Z}\\p{Z})\\d{4}(|\\p{Z}|\\p{Z}\\p{Z})-(|\\p{Z}|\\p{Z}\\p{Z})\\d{4}", "****-****-****-****"); // strOriginal = strOriginal.toString().replaceAll("\\d{4}(|\\p{Z}|\\p{Z}\\p{Z})~(|\\p{Z}|\\p{Z}\\p{Z})\\d{4}(|\\p{Z}|\\p{Z}\\p{Z})~(|\\p{Z}|\\p{Z}\\p{Z})\\d{4}(|\\p{Z}|\\p{Z}\\p{Z})~(|\\p{Z}|\\p{Z}\\p{Z})\\d{4}", "****~****~****~****"); return strOriginal.toString(); } public static String setReplaceNull(Object strOriginal, Object strReplace){ if(strOriginal == null || strOriginal.equals("") || strOriginal.equals("null")){ return strReplace.toString(); } return strOriginal.toString(); } public static void getZipFile(String path, String fileName) { File f = new File(path); //파일이름미포함 String files[] = f.list(); // f object 에 있는 파일목록 String outFilename = path + "/" + fileName + ".zip"; int number = 1; while (true) { File newFile = new File(outFilename); if (newFile != null && newFile.exists()) { outFilename = path + "/" + fileName + "_" + number + ".txt"; number++; } else { break; } } int size = 1024; //Create a buffer for reading the files byte[] buf = new byte[size]; //Create the ZIP file ZipOutputStream zos = null; FileInputStream fis = null; try{ zos = new ZipOutputStream(new FileOutputStream(outFilename)); //Compress the files if(files != null && files.length > 0){ for (int i = 0; i < files.length; i++) { fis = new FileInputStream(path + "/" + files[i]); //Add ZIP entry to output stream. zos.putNextEntry(new ZipEntry(files[i])); // Zip 파일에 경로를 정하여 저장할수 있다. //Transfer bytes from the file to the ZIP file int len; while ((len = fis.read(buf, 0, size)) > 0) { zos.write(buf, 0, len); } //Complete the entry zos.closeEntry(); fis.close(); } } //Complete the ZIP file zos.close(); }catch (FileNotFoundException e){ log.error("FileNotFoundException Error"); }catch (IOException e){ log.error("IOException Error"); }finally{ if (fis != null) { try{ fis.close(); }catch (IOException e){ log.error("IOException Error"); } } if (zos != null) { try{ zos.close(); }catch (IOException e){ log.error("IOException Error"); } } } } public static void setUnZipFile(String zipPath, String unzipPath) { File zipFile = new File(zipPath); //파일이름포함 File targetDir = new File(unzipPath); //미포함 FileInputStream fis = null; ZipInputStream zis = null; FileOutputStream fos = null; try{ fis = new FileInputStream(zipFile); zis = new ZipInputStream(fis); // ZipInputStream ZipEntry zentry = null; while ((zentry = zis.getNextEntry()) != null) { String fileNameToUnzip = zentry.getName(); File targetFile = new File(targetDir, fileNameToUnzip); if (zentry.isDirectory()) {// Directory 인 경우 File newDir = new File(targetFile.getAbsolutePath()); newDir.mkdirs(); } else { // File 인 경우 //parent Directory 생성 File newFile = new File(targetFile.getParent()); newFile.mkdirs(); fos = new FileOutputStream(targetFile); byte[] buffer = new byte[1024]; int len = 0; while ((len = zis.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); } } zis.close(); fis.close(); }catch (FileNotFoundException e){ log.error("FileNotFoundException Error"); }catch (IOException e){ log.error("IOException Error"); }finally{ if (fos != null) { try{ fos.close(); }catch (IOException e){ log.error("IOException Error"); } } if (zis != null) { try{ zis.close(); }catch (IOException e){ log.error("IOException Error"); } } if (fis != null) { try{ fis.close(); }catch (IOException e){ log.error("IOException Error"); } } } } public static String getRandomData (int length) { int index = 0; char[] charSet = new char[] { '0','1','2','3','4','5','6','7','8','9' ,'A','B','C','D','E','F','G','H','I','J','K','L','M' ,'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' ,'a','b','c','d','e','f','g','h','i','j','k','l','m' ,'n','o','p','q','r','s','t','u','v','w','x','y','z'}; StringBuffer sb = new StringBuffer(); for (int i=0; i 0){ sb.append(charSet[index]); } } return sb.toString(); } /** * random한 값을 얻고자 할때 사용하는 메소드 * 보안 관련 체크를 위해서 Math.random 이 아닌 SecureRandom을 이용해서 작업을 진행함 * 결과 값이 min값보다 작은경우 rendom함수 재호출 해서 값을 넘겨주는 방식 * @param int max 난수 최대값 * @param int min 난수 최소값 * @return int 난수값 * */ public static int getRandom(int max, int min){ int result = 0; SecureRandom ran = new SecureRandom(); result = ran.nextInt(max); return result < min ? getRandom(max,min) : result; } public static String getSeedWE8DECtoKor(String strData){ //ex.) UTL_RAW.CAST_TO_RAW(columnName) if (strData.length() % 2 != 0) { return ""; } StringBuffer buff = new StringBuffer(); int i = 0; while( i < strData.length() ){ buff.append((char)Integer.parseInt(strData.substring(i, i+2),16)); i = i + 2; } try{ if(buff.toString() != null){ return new String(buff.toString().getBytes("8859_1"), "EUC_KR"); }else{ return buff.toString(); } }catch(Exception ex){ return ex.toString(); } } public static String setTagRemove(String strOriginal){ String strRemove = ""; if(strOriginal != null && !"".equals(strOriginal)){ strRemove = strOriginal.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>", ""); } return strRemove; } public static boolean setChkFilePath(String filePath){ boolean chk = false; if(filePath != null && !"".equals(filePath)){ if(filePath.indexOf(".") >= 0){ chk = true; } } return chk; } public static Long getFolderSize(File file, Long volume){ File[] listFile = file.listFiles(); if(listFile != null && listFile.length > 0){ for(int i=0;i length){ int chkLoop = 0; for(int i=0; i= length){ returnStr = returnStr + "..."; break; } char ch = str.charAt(i); Character.UnicodeBlock unicodeBlock = Character.UnicodeBlock.of(ch); if(Character.UnicodeBlock.HANGUL_SYLLABLES.equals(unicodeBlock) || Character.UnicodeBlock.HANGUL_JAMO.equals(unicodeBlock) || Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO.equals(unicodeBlock)){ returnStr = returnStr+String.valueOf(ch); chkLoop = chkLoop+chkLen; }else{ returnStr = returnStr+String.valueOf(ch); chkLoop = chkLoop+1; } } }else{ returnStr = str; } } return returnStr; } public static String getJspContentTypeStr(){ return "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>"; } public static void setFileMkdirAuthSet(File dir){ if(dir != null){ dir.setExecutable(false, true); dir.setReadable(true); dir.setWritable(true, true); } } public static boolean getBrowserHtml5(String userAgent){ boolean success = true; //IE 버전일때 체크 if(userAgent.indexOf("msie") > -1 || userAgent.indexOf("trident/") > -1){ //IE6, IE7은 Trident 없음 if(userAgent.indexOf("trident/") <= -1){ success = false; }else{ if(userAgent.indexOf("trident/5.0") > -1){ //IE 9 success = false; }else if(userAgent.indexOf("trident/4.0") > -1){ //IE 8 success = false; } } } return success; } public static boolean getBrowserIE(String userAgent){ boolean success = false; //IE 버전일때 체크 if(userAgent.indexOf("msie") > -1 || userAgent.indexOf("trident/") > -1){ success = true; } return success; } /** * long형태의 데이터를 int형태로 변경하는 메소드 * 변경 실패시 IllegalArgumentException 발생 * */ public static int safeLongToInt(long l) { int i = (int)l; if ((long)i != l) { throw new IllegalArgumentException(l + " safeLongToInt에서 에러 발생"); } return i; } public static boolean isMobile(String userAgent){ boolean isMobile = false; userAgent = userAgent.toLowerCase(); String[] mobileKeyWord = {"iphone","ipod","android","blackberry","opera mini","opera mobi","skyfire","maemo","windows phone","palm","iemobile","symbian","symbianos","fennec"}; for(int i=0; i-1){ isMobile = true; break; } } return isMobile; } public static boolean isTablet(String userAgent){ boolean isTablet = false; userAgent = userAgent.toLowerCase(); String[] mobileKeyWord = {"ipad","android 3","sch-i800","playbook","tablet","kindle","gt-p1000","sgh-t849","shw-m180s","a510","a511","a100","dell streak","silk"}; for(int i=0; i-1){ isTablet = true; break; } } return isTablet; } public static String encodeURIComponent(String s) { String result = null; try{ result = URLEncoder.encode(s, "UTF-8") .replaceAll("\\+", "%20") .replaceAll("\\%21", "!") .replaceAll("\\%27", "'") .replaceAll("\\%28", "(") .replaceAll("\\%29", ")") .replaceAll("\\%7E", "~"); }catch (UnsupportedEncodingException e){result = s;} return result; } public static boolean isCookieChk(String cookieKey, int cookieHour, HttpServletRequest request, HttpServletResponse response){ try { if(cookieHour == 0){ return true; } SeedCookieUtil seedCookieUtil = new SeedCookieUtil(); String cookieVal = seedCookieUtil.getCookie(request, cookieKey); if (!("Y".equals(cookieVal))) { seedCookieUtil.setCookie(response, cookieHour * 24 * 60 * 60, "/", cookieKey, "Y", true); return true; } }catch (Exception localException){ log.error("Exception localException"); } return false; } /* public static String getCpuInfo() { String cpuInfo = ""; Sigar sigar = new Sigar(); CpuPerc cpu; try { cpu = sigar.getCpuPerc(); cpuInfo = CpuPerc.format(cpu.getUser()); } catch (SigarException e) { log.error("CHECK ERROR:",e); } return cpuInfo; } public static String getMemoryInfo() { String memoryInfo = ""; Sigar sigar = new Sigar(); Mem mem; try { mem = sigar.getMem(); memoryInfo = format(mem.getTotal()) + ":" + format(mem.getUsed()) + ":" + format(mem.getFree()); } catch (SigarException e) { log.error("CHECK ERROR:",e); } return memoryInfo; }*/ public static String format(Long value) { return Long.toString(new Long(value / 1024)); } }