2
0

base64.test.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright 2004-present the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. "use strict";
  17. import { expect } from "chai";
  18. import base64url from "../lib/base64url.js";
  19. describe("base64url", () => {
  20. before(() => {
  21. // Emulate the atob / btoa base64 encoding/decoding from the browser
  22. global.window = {
  23. btoa: (str) => Buffer.from(str, "binary").toString("base64"),
  24. atob: (b64) => Buffer.from(b64, "base64").toString("binary"),
  25. };
  26. });
  27. after(() => {
  28. // Reset window object
  29. global.window = {};
  30. });
  31. it("decodes", () => {
  32. // "Zm9vYmFy" is "foobar" in base 64, i.e. f:102 o:111 o:111 b:98 a:97 r:114
  33. const decoded = base64url.decode("Zm9vYmFy");
  34. expect(new Uint8Array(decoded)).to.be.deep.equal(new Uint8Array([102, 111, 111, 98, 97, 114]));
  35. });
  36. it("decodes special characters", () => {
  37. // Wrap the decode function for easy testing
  38. const decode = (str) => {
  39. const decoded = new Uint8Array(base64url.decode(str));
  40. return Array.from(decoded);
  41. };
  42. // "Pz8/" is "???" in base64, i.e. ?:63 three times
  43. expect(decode("Pz8/")).to.be.deep.equal(decode("Pz8_"));
  44. expect(decode("Pz8_")).to.be.deep.equal([63, 63, 63]);
  45. // "Pj4+" is ">>>" in base64, ie >:62 three times
  46. expect(decode("Pj4+")).to.be.deep.equal(decode("Pj4-"));
  47. expect(decode("Pj4-")).to.be.deep.equal([62, 62, 62]);
  48. });
  49. it("encodes", () => {
  50. const encoded = base64url.encode(Buffer.from("foobar"));
  51. expect(encoded).to.be.equal("Zm9vYmFy");
  52. });
  53. it("encodes special +/ characters", () => {
  54. const encode = (str) => base64url.encode(Buffer.from(str));
  55. expect(encode("???")).to.be.equal("Pz8_");
  56. expect(encode(">>>")).to.be.equal("Pj4-");
  57. });
  58. it("is stable", () => {
  59. const base = "tyRDnKxdj7uWOT5jrchXu54lo6nf3bWOUvMQnGOXk7g";
  60. expect(base64url.encode(base64url.decode(base))).to.be.equal(base);
  61. });
  62. });