|
1 | | -const base64 = require("@hexagon/base64"); |
2 | | - |
3 | 1 | const ApiError = require("./error"); |
4 | 2 |
|
5 | 3 | /** |
@@ -101,14 +99,45 @@ async function createHMACSHA256(secret, data) { |
101 | 99 |
|
102 | 100 | const key = await crypto.subtle.importKey( |
103 | 101 | "raw", |
104 | | - base64.toArrayBuffer(secret), |
| 102 | + base64ToBytes(secret), |
105 | 103 | { name: "HMAC", hash: "SHA-256" }, |
106 | 104 | false, |
107 | 105 | ["sign"] |
108 | 106 | ); |
109 | 107 |
|
110 | 108 | const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(data)); |
111 | | - return base64.fromArrayBuffer(signature); |
| 109 | + return bytesToBase64(signature); |
| 110 | +} |
| 111 | + |
| 112 | +/** |
| 113 | + * Convert a base64 encoded string into bytes. |
| 114 | + * |
| 115 | + * @param {string} the base64 encoded string |
| 116 | + * @return {Uint8Array} |
| 117 | + * |
| 118 | + * Two functions for encoding/decoding base64 strings using web standards. Not |
| 119 | + * intended to be used to encode/decode arbitrary string data. |
| 120 | + * See: https://developer.mozilla.org/en-US/docs/Glossary/Base64#javascript_support |
| 121 | + * See: https://stackoverflow.com/a/31621532 |
| 122 | + * |
| 123 | + * Performance might take a hit because of the conversion to string and then to binary, |
| 124 | + * if this is the case we might want to look at an alternative solution. |
| 125 | + * See: https://jsben.ch/wnaZC |
| 126 | + */ |
| 127 | +function base64ToBytes(base64) { |
| 128 | + return Uint8Array.from(atob(base64), (m) => m.codePointAt(0)); |
| 129 | +} |
| 130 | + |
| 131 | +/** |
| 132 | + * Convert a base64 encoded string into bytes. |
| 133 | + * |
| 134 | + * See {@link base64ToBytes} for caveats. |
| 135 | + * |
| 136 | + * @param {Uint8Array | ArrayBuffer} the base64 encoded string |
| 137 | + * @return {string} |
| 138 | + */ |
| 139 | +function bytesToBase64(bytes) { |
| 140 | + return btoa(String.fromCharCode.apply(null, new Uint8Array(bytes))); |
112 | 141 | } |
113 | 142 |
|
114 | 143 | /** |
|
0 commit comments