반응형

텍스트를 요청 파라미터로 넣으면

암호화된 값을 리턴합니다.

Sha256Encryption: function (ascii) {
            /**
             * sha256 암호화 
             * 암호화된 text를 출력한다.
             */
            function rightRotate(value, amount) {
                return (value>>>amount) | (value<<(32 - amount));
            };

            var mathPow = Math.pow;
            var maxWord = mathPow(2, 32);
            var lengthProperty = 'length'
            var i, j; // Used as a counter across the whole file
            var result = ''

            var words = [];
            var asciiBitLength = ascii[lengthProperty]*8;

            //* caching results is optional - remove/add slash from front of this line to toggle
            // Initial hash value: first 32 bits of the fractional parts of the square roots of the first 8 primes
            // (we actually calculate the first 64, but extra values are just ignored)
            var hash = this.Sha256Encryption.h = this.Sha256Encryption.h || [];
            // Round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes
            var k = this.Sha256Encryption.k = this.Sha256Encryption.k || [];
            var primeCounter = k[lengthProperty];
            /*/
            var hash = [], k = [];
            var primeCounter = 0;
            //*/

            var isComposite = {};
            for (var candidate = 2; primeCounter < 64; candidate++) {
                if (!isComposite[candidate]) {
                    for (i = 0; i < 313; i += candidate) {
                        isComposite[i] = candidate;
                    }
                    hash[primeCounter] = (mathPow(candidate, .5)*maxWord)|0;
                    k[primeCounter++] = (mathPow(candidate, 1/3)*maxWord)|0;
                }
            }

            ascii += '\x80' // Append Ƈ' bit (plus zero padding)
            while (ascii[lengthProperty]%64 - 56) ascii += '\x00' // More zero padding
            for (i = 0; i < ascii[lengthProperty]; i++) {
                j = ascii.charCodeAt(i);
                if (j>>8) return; // ASCII check: only accept characters in range 0-255
                words[i>>2] |= j << ((3 - i)%4)*8;
            }
            words[words[lengthProperty]] = ((asciiBitLength/maxWord)|0);
            words[words[lengthProperty]] = (asciiBitLength)

            // process each chunk
            for (j = 0; j < words[lengthProperty];) {
                var w = words.slice(j, j += 16); // The message is expanded into 64 words as part of the iteration
                var oldHash = hash;
                // This is now the undefinedworking hash", often labelled as variables a...g
                // (we have to truncate as well, otherwise extra entries at the end accumulate
                hash = hash.slice(0, 8);

                for (i = 0; i < 64; i++) {
                    var i2 = i + j;
                    // Expand the message into 64 words
                    // Used below if 
                    var w15 = w[i - 15], w2 = w[i - 2];

                    // Iterate
                    var a = hash[0], e = hash[4];
                    var temp1 = hash[7]
                        + (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) // S1
                        + ((e&hash[5])^((~e)&hash[6])) // ch
                        + k[i]
                        // Expand the message schedule if needed
                        + (w[i] = (i < 16) ? w[i] : (
                                w[i - 16]
                                + (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15>>>3)) // s0
                                + w[i - 7]
                                + (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2>>>10)) // s1
                            )|0
                        );
                    // This is only used once, so *could* be moved below, but it only saves 4 bytes and makes things unreadble
                    var temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) // S0
                        + ((a&hash[1])^(a&hash[2])^(hash[1]&hash[2])); // maj

                    hash = [(temp1 + temp2)|0].concat(hash); // We don't bother trimming off the extra ones, they're harmless as long as we're truncating when we do the slice()
                    hash[4] = (hash[4] + temp1)|0;
                }

                for (i = 0; i < 8; i++) {
                    hash[i] = (hash[i] + oldHash[i])|0;
                }
            }

            for (i = 0; i < 8; i++) {
                for (j = 3; j + 1; j--) {
                    var b = (hash[i]>>(j*8))&255;
                    result += ((b < 16) ? 0 : '') + b.toString(16);
                }
            }
            return result;
        }

 

암호화된 값은 : https://md5decrypt.net/en/Sha256/

 

Sha256 Decrypt & Encrypt - More than 15.000.000.000 hashes

 

md5decrypt.net

 

여기서 확인 가능합니다.

반응형
반응형

보통 다음 페이지로 이동할 때 location.href  URL 을 넣어서 이동을 시키게 됩니다. 그럼 뒤로 가기가 가능해 집니다. 브라우저에 뒤로 가기 버튼이 활성화 되죠. 이렇게 뒤로 가기가 되지 않도록 페이지 이동을 시킬 수가 있습니다.

 

 어떤 웹 사이트에서는 보안상의 이유로 뒤로 가기가 안되도록 구현하는 곳이 있습니다. 먼저 뒤로 가기가 되는 일반적인 경우를 보겠습니다. 페이지 이동을 위해 버튼을 클릭했을 때 move 함수를 실행하도록 만들었습니다. 페이지 이동은 location.href 를 변수를 사용합니다.

 

<!DOCTYPE HTML> 
<html> 
	<head> 
		<meta content="text/html; charset=euc-kr"> 
		<title>페이지 이동 </title> 
	</head> 
	<script type="text/javascript"> 
		function move(){ 
        	location.href="history02.html"; 
        } 
	</script> 
	<body> 첫 번째 페이지 입니다.<br/><br/> 
		<input type="button" value="다음>" onClick="javascript:move();"> 
	</body> 
</html>

 위의 소스를 실행했을 때 이동한 history02.html 페이지에서 웹 브라우저 뒤로 가기 버튼이 활성화 되어 있는 것을 알 수 있습니다. 그러니까 이동이 가능하다는 것이죠.

 

 브라우저에 뒤로 가기 버튼을 비활성화 시키려면 이전 이력이 남지 않는 replace 함수를 사용해야 합니다. location 객체의 replace() 함수 파라미터로 이동할 주소를 넣으시면 됩니다.

 

<!DOCTYPE HTML> 
<html> 
<head> 
	<meta content="text/html; charset=euc-kr"> 
	<title>페이지 이동 </title> 
</head>
	<script type="text/javascript"> 
	function move(){
		location.replace("history02.html");
	} 
	</script> 
<body> 첫 번째 페이지 입니다.<br/><br/> 
	<input type="button" value="다음>" 
	onClick="javascript:move();"> 
</body> 
</html>

 

 아래 그림처럼 location.replace() 함수를 이용해서 다음 페이지로 이동시키면 상단에 있는 브라우저 이전 버튼은 활성화가 되어 있지 않습니다 



출처: https://mainia.tistory.com/2806 [녹두장군 - 상상을 현실로]

반응형
반응형

웹 페이지 개발 중 특정 HTML 요소에 onClick 이벤트를 발생 시 이미지 변경 또는 특정 효과를 주기 위해 class 를 추가 제거 하는 상황들이 많이 발생하게 됩니다.

 

물론 큰 사이트 개발이나 유지 보수를 하는 경우라면 개발자 입장에서는 위와 같은 경우를 컨트롤 할 필요가 거의 없습니다. UI / UX 개발 담당자들 또는 퍼블리셔들이 이미 해당 HTML 요소(Check box, Radio box 등등)의 click 이벤트에 대해 처리를 해두었기 때문입니다. 

 

하지만 소규모 프로젝트에서 일반적으로 퍼블을 전달 받았을때 스크립트 적용은 되어 있지 않은 경우가 거의 대부분입니다. 

 

그렇다면 HTML 요소의 class 변경을 어떻게 해야 할까요? 

<input id="chkBox" type="checkbox" class="on"
onclick="javascript:chkBoxImageChange();" checked/>

위 코드는 간단한 체크 박스를 표기 합니다. 

 

기본 checked / unchecked 이미지를 사용 하지 않습니다.  

class 명이 on 일경우 check 된 스타일의 이미지를 입히고, 

class 명이 빈값일 경우 unchecked 된 스타일의 이미지를 입힌다고 가정 하겠습니다. 

 

chkBoxImageChange() 함수는 아래와 같이 작성하면 됩니다. 

<script type="text/javascript">

window.chkBoxImageChange = function() {
if(document.getElementById('chkBox').getAttribute('class') == 'on')
{
document.getElementById('chkBox').setAttribute('class', '');
} else {
document.getElementById('chkBox').setAttribute('class', 'on');
};
};

</script>

 

class 명이 on 이면 id 값이 chkBox 인 요소의 속성 값 중 class 를 빈값으로 바꾸고 

class 명이 빈값이면 id 값이 chkBox 인 요소의 속성 값 중 class 를 on 으로 바꾸는 코드 입니다. 

 

 

위와 같이 작성 할 수 있지만 HTML5 에서는 위와 같은 수고스러움을 모두 덜어 주고 있습니다. 

<script type="text/javascript">

window.fncShowHideList = function() {
document.getElementById('chkBox').classList.toggle('on');
};

</script>

HTML5에서는 classList 라는 속성을 제공하고 있는데요. 이녀석은 class 값을 더욱 쉽게 가지고 놀수 있도록 도와 주고 있습니다. 

 

classList.toggle('class명') 이라고 작성 했을 경우 class명이 존재 하면 삭제를 하고 존재하지 않을 경우 추가를 하는 동작을 합니다. 

 

jQuery 의 toggle 과 동일한 동작을 하는 거죠. 다만 jQeury 는 사용하기 위해 Library 를 추가 해야 하지만 HTML5 는 그럴 필요가 없다는 겁니다. 

 

 

Element.classList 사용 예를 추가로 보여드리겠습니다. 

div.classList.remove("foo");
div.classList.add("newclass");

<div> 태그 class 명에 foo 값이 있으면 제거하고 newclass 라는 class 명을 추가 합니다. 

 

div.classList.toggle("visible");

첫 샘플에서는 getElementById('id') 로 해당 ID값에 대해 class 추가 / 삭제 여부를 결정 했다면 이번에는 <div> 태그 전체에서 class 명 중 visible 있으면 삭제하고 없으면 추가 하는 명령입니다. 

 

div.classList.toggle("visible", i < 10 );

for loop 이나 while loop 을 돌리고 있을 경우 i 값으로 카운트 한다고 가정했을때 i 값이 10보자 작을 경우에만 class 명이 visible 이 있으면 삭제하고 없으면 추가 하는 명령입니다. i 값이 10보다 커지면 아무 동작 하지 않습니다. 

 

alert(div.classList.contains("foo"));

contains 라는 함수가 보이는 데요. 이는 foo 라는 class 명이 있으면 true 를 리턴하고 없으면 false 를 리턴합니다. 

 

div.classList.add("foo", "bar");
div.classList.remove("foo", "bar");

class 명을 , 로 구분하여 한번에 여러 class 명을 추가 / 삭제 하는 명령입니다. 

 

 

IE 10 에서는 동작하지 않는 다는 글이 있습니다. (제가 테스트 해보지는 못했습니다. 테스트 후 확인 되면 명확하게 내용 추가 하도록 하겠습니다. )

그래서 PC 환경에서는 적용하기 약간은 부담이 될 수도 있지만 모바일 환경이라면 마음 놓고 사용하셔도 문제 없을 것 같습니다. 



출처: https://jamesdreaming.tistory.com/21 [Dev Life in IT]

반응형
반응형

현재 접속한 기기의 IP를 받아오는 소스

<script type="text/javascript" src="http://jsgetip.appspot.com"></script>
<script>
    $(document).ready(function(){
        var check_ip = ip();           // 접속한 기기의 IP를 가져온다
        alert(check_ip);                
    });
</script>

특정 IP 만 허용 & 차단하기

<script type="text/javascript" src="http://jsgetip.appspot.com"></script>
<script>
    $(document).ready(function(){
        var check_ip = ip();           // 접속한 기기의 IP를 가져온다
        var AllowIP = ["49.166.205.145","192.168.35.172","58.124.178.106","175.208.239.21","223.38.17.123"];     // 허용할 IP 배열
        var DenyIP = ["223.38.17.123"];     // 차단할 IP 배열
        var i = 0;
                 
        for (var i in AllowIP){
            if (AllowIP[i] == check_ip) {
                    // 허용 IP에 대한 이벤트
            }
        }
        for (var i in DenyIP){
            if (DenyIP[i] == check_ip) {
                    // 차단 IP에 대한 이벤트
            }
        }
    });
</script>

IP로 접속 국가 확인

<script>
var ip = "";
var hostname = "";
var city = "";
var region = "";
var country = "";
var loc = "";
var org = "";
  
$.getJSON("http://ipinfo.io", function(data) {
    ip = data.ip // 접속자 ip
    hostname = data.hostname // 접속자 hostname
    city = data.city // 접속자 도시
    region = data.region // 접속자 지역
    country = data.country // 접속자 국가
    loc = data.loc // 접속 위도, 경도
    org = data.org // ISP (인터넷 서비스 제공사업자)
     
    // 지역별 분기
    if(country == "KR"){
        console.log(data);
    } else if(country == "CN"){
        console.log(data);
    } else {
        console.log(data);
    }
});
</script>

국가 코드는 링크의 json을 참조하시면 됩니다. http://country.io/names.json

 

참조: https://sbss.tistory.com/11

반응형

+ Recent posts