[javascript] js base64 encode / js base64 decode

[javascript] js base64 encode / js base64 decode

크롬에서는 js base64 인코딩 시 btoa 함수를 사용, js base64 디코딩시 atob 함수를 사용하면 된다.

그런데 IE에서는 해당 함수가 구현되어 있지 않다.

base64 인코딩이나 디코딩을 하는 jsp 또는 html 페이지에 다음 js를 임포트하여 btoa, atob 함수를 구현한다.

base64.js (첨부된 base64_js.txt 를 다운로드 받아 확장자 변경할 것)

 (function() {
    window.btoa || (
    window.btoa = function(input) {
        var chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=’;
        var str = String (input);
        for (var block, charCode, idx = 0, map = chars, output = ”;
            str.charAt (idx | 0) || (map = ‘=’, idx % 1);
            output += map.charAt (63 & block >> 8 – idx % 1 * 8)) {
            charCode = str.charCodeAt (idx += 3 / 4);
            if (charCode > 0xFF) {
                alert(“btoa failed : The string to be encoded contains characters outside of the Latin1 range.”);
                return input;
            }
            block = block << 8 | charCode;
        }
        return output;
    });

    window.atob || (
    window.atob = function(input) {
        var chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=’;
        var str = (String (input)).replace (/[=]+$/, ”);
        if (str.length % 4 === 1) {
            alert(“atob failed : The string to be decoded is not correctly encoded.”);
            return input;
        }
        for (var bc = 0, bs, buffer, idx = 0, output = ”;
            buffer = str.charAt (idx++);
            ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, bc++ % 4) ? output += String.fromCharCode (255 & bs >> (-2 * bc & 6)) : 0) {
            buffer = chars.indexOf (buffer);
        }
        return output;
    });
} ());

함수 사용은 아래와 같이 한다. (참고사이트 2 읽어보기)

function encodeBase64(_str) {
    return btoa(encodeURIComponent(_str));
}
   
function decodeBase64(_str) {
    return decodeURIComponent(atob(_str));
}

마지막 팁. 만약 base64 인코딩한 값을 특정 URL에 파라미터로 붙여 보내야 한다면(get 방식), encodeBase64 한 결과에 encodeURIComponent 를 씌워주는 것이 안전하다.

ex)  var encParam1 = encodeBase64(originParam1);

var targetUrl = “프로토콜://도메인명?param1= + encodeURIComponent(encParam1)

2020/08/03 내용추가

https://blog.naver.com/bb_/222049859684

참고사이트 1) https://coderanch.com/t/630782/languages/window-btoa-supported

참고사이트 2) https://stackoverflow.com/questions/30631927/converting-to-base64-in-javascript-without-deprecated-escape-call