본문 바로가기
JSP

[ JSP ] form데이터 간단한 암호화 및 특수문자 해결, urlencoding,decoding

by 정윤재 2008. 10. 20.

암호화를 했을때 문제는 거의 대부분의 암호화된 문자들이 특수문자로 바뀌어  페이지가 넘어갈때 특수문자가 깨진다는데 있을 것입니다. 이런 문제를 어떻게 해결해야 할까요? UTF-8로 바꿔주면 된다고 말씀하시겠지만... 일단 고전적인 방법인 URL Encoding을 써보겠습니다.
이놈의 암호화 때문에 얼마나 고생했는지... 별것 아닌 암호화 입니다.
Random 으로 숫자를 생성해서 그것을 더해주고 더한 숫자를 나중에 붙여서 복호화할때 알아보라고 해놓은거죠.

loginTest.jsp -> loginView.jsp -> utiTest.java

loginTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script>
function sub(){
 var encId=Encrypt(f1.id.value);
 //암호화
 var encPw=Encrypt(f1.pw.value);
 
 
 alert("encId====>"+encId);
 alert("encPw====>"+encPw);
 
 var urlId=encodeURL(encId);
 //URL encoding
 var urlPw=encodeURL(encPw);
 f1.id.value=urlId;
 f1.pw.value=urlPw;
 f1.submit();
}
// 암호화
function Encrypt(theText){
           output = new String;
           Temp = new Array();
           Temp2 = new Array();
           TextSize = theText.length;
          
           for (i = 0; i < TextSize; i++) { 
                     rnd = Math.round(Math.random() * 122) + 68; 
                     Temp[i] = theText.charCodeAt(i) + rnd; 
                     Temp2[i] = rnd;
           }
          
           for (i = 0; i < TextSize; i++) { 
                     output += String.fromCharCode(Temp[i], Temp2[i]);
           }
          
           return output;
}
//url 인코딩
function encodeURL(str){
    var s0, i, s, u;
    s0 = "";                // encoded str
    for (i = 0; i < str.length; i++){   // scan the source
        s = str.charAt(i);
        u = str.charCodeAt(i);          // get unicode of the char
        if (s == " "){s0 += "+";}       // SP should be converted to "+"
        else {
            if ( u == 0x2a || u == 0x2d || u == 0x2e || u == 0x5f || ((u >= 0x30) && (u <= 0x39)) || ((u >= 0x41) && (u <= 0x5a)) || ((u >= 0x61) && (u <= 0x7a))){       // check for escape
                s0 = s0 + s;            // don't escape
            }
            else {                  // escape
                if ((u >= 0x0) && (u <= 0x7f)){     // single byte format
                    s = "0"+u.toString(16);
                    s0 += "%"+ s.substr(s.length-2);
                }
                else if (u > 0x1fffff){     // quaternary byte format (extended)
                    s0 += "%" + (0xf0 + ((u & 0x1c0000) >> 18)).toString(16);
                    s0 += "%" + (0x80 + ((u & 0x3f000) >> 12)).toString(16);
                    s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                    s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
                }
                else if (u > 0x7ff){        // triple byte format
                    s0 += "%" + (0xe0 + ((u & 0xf000) >> 12)).toString(16);
                    s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                    s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
                }
                else {                      // double byte format
                    s0 += "%" + (0xc0 + ((u & 0x7c0) >> 6)).toString(16);
                    s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
                }
            }
        }
    }
    return s0;
}

</script>
</head>
<body>
<center>
 <form name="f1" method="post"  action="loginView.jsp"> 
  <table border="1">
   
    <tr><td>아이디</td><td><input type="text" name="id"></td></tr>
    <tr><td>비밀번호</td><td><input type="text" name="pw"></td></tr>
  
  </table>
  
  <input type="button" value="전송" onClick="sub()"> 
 </form>
  
</center>  
</body>
</html>

///////////////////////////////////////////////////////////////
loginView.jsp

<%@ page language="java"  import="java.net.*,java.util.*,com.*" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>

<title>Insert title here</title>
</head>
<body>
<%

 utilTest test=new utilTest();
 String id=request.getParameter("id");
 id= new String(id.getBytes("8859_1"),"UTF-8");
 //혹시 모르니 UTF-8로 바꿈(EUC-KR로 해도 상관은 없을듯)
 id=URLDecoder.decode(id, "UTF-8");
 id=test.StrtoUni(id);
 id=test.UnitoStr(id);
 
 String pw=request.getParameter("pw");
 pw= new String(pw.getBytes("8859_1"),"UTF-8");
 pw=URLDecoder.decode(pw, "UTF-8");
 pw=test.StrtoUni(pw);
 pw=test.UnitoStr(pw);
%>


<%=id%><br>
<%=pw%>
</body>
</html>
//////////////////////////////////////////////////
utilTest.java

package com;

import java.util.StringTokenizer;
 
public class utilTest {
 //유니코드를 String 으로 바꿔주는 또는 반대로 해주는 메소드들
 public String StrtoUni(String str){
  String uni="";
  for(int i=0;i<str.length();i++){
   
   if((i+1)%2==1){
    char char1=str.charAt(i);
    char char2=str.charAt(i+1);
    char chr=(char) (char1-char2);
    String hex=Integer.toHexString(chr);
    uni+="
\\u"+hex;
   }
    
  }
  return uni;
 }
 
 public String UnitoStr(String uni){
  
  String str="";
  StringTokenizer str1=new StringTokenizer(uni,"
\\u");
  
  while(str1.hasMoreTokens()){
   String str2=str1.nextToken();
   int i=Integer.parseInt(str2,16);
   str+=(char)i;
   
  }
  return str;
 }
}


댓글