最近做个项目, 需要用js来进行base64 encode, 然后用perl来base64 decoce. 做完之后, 记录一下.
首先是javascript的base64 encode, 查了下, 要么是用jquery, 要么就是自己定义base64encode的方法. 选择了后者.
<script> var paraStr = "in=1&"+location.href.substring(location.href.indexOf("?")+1); paraStr = base64Encode(paraStr); var hostUrl = '<% get_host_url %>'; var join = '?'; if(hostUrl.indexOf('?') != -1) join = '&'; window.top.location = hostUrl + join + 'redirect_data=' + paraStr; // function uTF8Encode function uTF8Encode(string){ string = string.replace(/\x0d\x0a/g, "\x0a"); var output = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { output += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { output += String.fromCharCode((c >> 6) | 192); output += String.fromCharCode((c & 63) | 128); } else { output += String.fromCharCode((c >> 12) | 224); output += String.fromCharCode(((c >> 6) & 63) | 128); output += String.fromCharCode((c & 63) | 128); } } return output; } // function base64Encode function base64Encode(input){ var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = uTF8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4); } return output; }</script>
其中uTF8Encode和base64Encode 来自jquery插件. 类似的还有base64 decode的两个方法.
也可参考, 这里只是没有转utf-8.
至于perl的 就简单了, 直接引用模块:
use MIME::Base64 qw(encode_base64 decode_base64);