자바스크립트 base64_decode()

1 개요[ | ]

JavaScript base64_decode()
자바스크립트 base64_decode()

2 순수 자바스크립트[ | ]

function utf8_decode( str ) {  
  var arr = [], i = ac = c1 = c2 = c3 = 0;  
  str += '';
  while ( i < str.length ) {  
    c1 = str.charCodeAt(i++); if (c1 < 128) { arr[ac++] = String.fromCharCode(c1); continue; }
    c2 = str.charCodeAt(i++); if (c1>191 && c1<224){ arr[ac++] = String.fromCharCode(((c1&31)<<6)|(c2&63)); continue; }
    c3 = str.charCodeAt(i++); arr[ac++] = String.fromCharCode(((c1&15)<<12)|((c2&63)<<6)|(c3&63));  
  }
  return arr.join('');
}  
function base64_decode(input) {
  var keystr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var output = "";
  var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  var i = 0;
  if( /[^A-Za-z0-9\+\/\=]/g.exec(input) ) return null;
  while(i < input.length) {
    enc1 = keystr.indexOf(input.charAt(i++));
    enc2 = keystr.indexOf(input.charAt(i++));
    enc3 = keystr.indexOf(input.charAt(i++));
    enc4 = keystr.indexOf(input.charAt(i++));
    chr1 = (enc1 << 2) | (enc2 >> 4);
    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    chr3 = ((enc3 & 3) << 6) | enc4;
    output = output + String.fromCharCode(chr1);
    if(enc3 != 64) output += String.fromCharCode(chr2);
    if(enc4 != 64) output += String.fromCharCode(chr3);
  }
  return utf8_decode(output);
}
console.log(base64_decode('안녕')); // (null)
console.log(base64_decode('aGVsbG8gd29ybGQ=')); // hello world
console.log(base64_decode('4piFQeqwgOOBguS4rQ==')); // ★A가あ中

3 CryptoJS 활용[ | ]

console.log( CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse('4piFQeqwgOOBguS4rQ==')) );
// ★A가あ中

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}