webAuthnHelper.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright (c) 2019 GitHub, Inc.
  2. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
  3. // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  4. // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  5. // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  6. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  9. // DEALINGS IN THE SOFTWARE.
  10. // below is from https://github.com/github/webauthn-json/tree/66322fc5c12184c5269691ab5abaac79545a3916
  11. export function base64urlToBuffer(baseurl64String: string): ArrayBuffer {
  12. // Base64url to Base64
  13. const padding = '=='.slice(0, (4 - (baseurl64String.length % 4)) % 4);
  14. const base64String = baseurl64String.replace(/-/g, '+').replace(/_/g, '/') + padding;
  15. // Base64 to binary string
  16. const str = atob(base64String);
  17. // Binary string to buffer
  18. const buffer = new ArrayBuffer(str.length);
  19. const byteView = new Uint8Array(buffer);
  20. for (let i = 0; i < str.length; i++) {
  21. byteView[i] = str.charCodeAt(i);
  22. }
  23. return buffer;
  24. }
  25. export function bufferToBase64url(buffer: ArrayBuffer): string {
  26. // Buffer to binary string
  27. const byteView = new Uint8Array(buffer);
  28. let str = '';
  29. for (const charCode of byteView) {
  30. str += String.fromCharCode(charCode);
  31. }
  32. // Binary string to base64
  33. const base64String = btoa(str);
  34. // Base64 to base64url
  35. // We assume that the base64url string is well-formed.
  36. const base64urlString = base64String
  37. .replace(/\+/g, '-')
  38. .replace(/\//g, '_')
  39. .replace(/=/g, '');
  40. return base64urlString;
  41. }