js-keygen/base64url.js

32 lines
1 KiB
JavaScript
Raw Normal View History

2018-02-13 16:41:00 +00:00
// adapted from https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-08#appendix-C
2015-09-03 11:58:00 +00:00
2015-09-04 07:13:08 +00:00
function base64urlEncode(arg) {
2018-02-13 16:41:00 +00:00
const step1 = window.btoa(arg); // Regular base64 encoder
const step2 = step1.split("=")[0]; // Remove any trailing '='s
const step3 = step2.replace(/\+/g, "-"); // 62nd char of encoding
const step4 = step3.replace(/\//g, "_"); // 63rd char of encoding
return step4;
2015-09-03 11:58:00 +00:00
}
2015-09-04 07:13:08 +00:00
function base64urlDecode(s) {
2018-02-13 16:41:00 +00:00
const step1 = s.replace(/-/g, "+"); // 62nd char of encoding
const step2 = step1.replace(/_/g, "/"); // 63rd char of encoding
let step3 = step2;
switch (step2.length % 4) { // Pad with trailing '='s
2018-02-13 08:30:29 +00:00
case 0: // No pad chars in this case
break;
case 2: // Two pad chars
2018-02-13 16:41:00 +00:00
step3 += "==";
2018-02-13 08:30:29 +00:00
break;
case 3: // One pad char
2018-02-13 16:41:00 +00:00
step3 += "=";
2018-02-13 08:30:29 +00:00
break;
default:
2018-02-13 16:41:00 +00:00
throw new Error("Illegal base64url string!");
2015-09-03 11:58:00 +00:00
}
2018-02-13 16:41:00 +00:00
return window.atob(step3); // Regular base64 decoder
2015-09-04 07:13:08 +00:00
}
2018-02-13 08:45:06 +00:00
2018-02-13 16:41:00 +00:00
const module = window.module || {};
2018-02-13 08:45:06 +00:00
module.exports = { base64urlDecode, base64urlEncode };