UNPKG

1.25 kBJavaScriptView Raw
1import { CodedError } from '@unimodules/core';
2import { CryptoEncoding } from './Crypto.types';
3export default {
4 get name() {
5 return 'ExpoCrypto';
6 },
7 async digestStringAsync(algorithm, data, options) {
8 if (!crypto.subtle) {
9 throw new CodedError('ERR_CRYPTO_UNAVAILABLE', 'Access to the WebCrypto API is restricted to secure origins (https).');
10 }
11 const encoder = new TextEncoder();
12 const buffer = encoder.encode(data);
13 const hashedData = await crypto.subtle.digest(algorithm, buffer);
14 if (options.encoding === CryptoEncoding.HEX) {
15 return hexString(hashedData);
16 }
17 else if (options.encoding === CryptoEncoding.BASE64) {
18 return btoa(String.fromCharCode(...new Uint8Array(hashedData)));
19 }
20 throw new CodedError('ERR_CRYPTO_DIGEST', 'Invalid encoding type provided.');
21 },
22};
23function hexString(buffer) {
24 const byteArray = new Uint8Array(buffer);
25 const hexCodes = [...byteArray].map(value => {
26 const hexCode = value.toString(16);
27 const paddedHexCode = hexCode.padStart(2, '0');
28 return paddedHexCode;
29 });
30 return hexCodes.join('');
31}
32//# sourceMappingURL=ExpoCrypto.web.js.map
\No newline at end of file