Skip to content

Instantly share code, notes, and snippets.

@kawaz
Last active March 24, 2023 05:42
Show Gist options
  • Save kawaz/e6893a9126cea1681e2430d6dc36a186 to your computer and use it in GitHub Desktop.
Save kawaz/e6893a9126cea1681e2430d6dc36a186 to your computer and use it in GitHub Desktop.
CloudFront Functions 内でコピペで使えるBASE64実装
// CloudFront Functions 内で利用可能なBASE64実装
function b64enc(b) {
var b64codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split("").map(s=>s.charCodeAt(0))
var pad = [0, 2, 1][b.length % 3]
// 入力バイト列(本来は 0xFF を超える charCode が含まれていたらエラーにすべきだが省略
var bCodes = (b + '\0'.repeat(pad)).split("").map(s=>s.charCodeAt(0))
// 出力用バイト列
var aCodes = new Uint8Array(bCodes.length / 3 * 4)
for(var i=0,j=0; i<b.length; i+=3,j+=4){
var b8x3 = bCodes[i]<<16 | bCodes[i+1]<<8 | bCodes[i+2]
var b6x4 = [b8x3>>18 & 63, b8x3>>12 & 63, b8x3>>6 & 63, b8x3 & 63]
aCodes.set(b6x4.map(i=>b64codes[i]), j)
}
aCodes.fill(b64codes[64], aCodes.length - pad)
return String.fromCharCode.apply(null, aCodes)
}
function b64dec(a) {
if(String.bytesFrom) {
// CFFunctions環境専用ポリフィル
return String.bytesFrom(a, "base64")
}
// そこに無ければ無いですね
return globalThis.atob(a)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment