1import { Platform } from 'expo-core'; 2import * as Crypto from 'expo-crypto'; 3 4const { CryptoEncoding, CryptoDigestAlgorithm } = Crypto; 5 6const testValue = 'Expo'; 7 8const valueMapping = { 9 [CryptoEncoding.HEX]: { 10 [CryptoDigestAlgorithm.SHA1]: `c275355dc46ac171633935033d113e3872d595e5`, 11 [CryptoDigestAlgorithm.SHA256]: `f5e5cae536b49d394e1e72d4368d64b00a23298ec5ae11f3a9102a540e2532dc`, 12 [CryptoDigestAlgorithm.SHA384]: `aa356c88afdbd8a7a5a9c3133541af0035e4b04e82438a223aa1939240ccb6b3ca28294b5ac0f42703b15183f4c016fc`, 13 [CryptoDigestAlgorithm.SHA512]: `f1924f3e61aac4e4caa7fd566591b8abb541b0e642cd7bf0c71573267cfacf1b6dafe905bd6e42633bfba67c59774e070095e19a7c2078ac18ccd23245d76f1c`, 14 [CryptoDigestAlgorithm.MD2]: `fb85323c3b15b016e0351006e2f47bf7`, 15 [CryptoDigestAlgorithm.MD4]: `2d36099794ec182cbb36d02e1188fc1e`, 16 [CryptoDigestAlgorithm.MD5]: `c29f23f279126757ba18ec74d0d27cfa`, 17 }, 18 [CryptoEncoding.BASE64]: { 19 [CryptoDigestAlgorithm.SHA1]: `wnU1XcRqwXFjOTUDPRE+OHLVleU=`, 20 [CryptoDigestAlgorithm.SHA256]: `9eXK5Ta0nTlOHnLUNo1ksAojKY7FrhHzqRAqVA4lMtw=`, 21 [CryptoDigestAlgorithm.SHA384]: `qjVsiK/b2KelqcMTNUGvADXksE6CQ4oiOqGTkkDMtrPKKClLWsD0JwOxUYP0wBb8`, 22 [CryptoDigestAlgorithm.SHA512]: `8ZJPPmGqxOTKp/1WZZG4q7VBsOZCzXvwxxVzJnz6zxttr+kFvW5CYzv7pnxZd04HAJXhmnwgeKwYzNIyRddvHA==`, 23 [CryptoDigestAlgorithm.MD2]: `+4UyPDsVsBbgNRAG4vR79w==`, 24 [CryptoDigestAlgorithm.MD4]: `LTYJl5TsGCy7NtAuEYj8Hg==`, 25 [CryptoDigestAlgorithm.MD5]: `wp8j8nkSZ1e6GOx00NJ8+g==`, 26 }, 27}; 28 29export const name = 'Crypto'; 30 31function supportedAlgorithm(algorithm) { 32 if (Platform.OS === 'web' && ['MD2', 'MD4', 'MD5'].includes(algorithm)) { 33 return false; 34 } 35 return true; 36} 37 38export async function test({ describe, it, expect }) { 39 describe('Crypto', () => { 40 describe('digestStringAsync()', async () => { 41 it(`Invalid CryptoEncoding throws an error`, async () => { 42 let error = null; 43 try { 44 await Crypto.digestStringAsync(CryptoDigestAlgorithm.SHA1, testValue, { 45 encoding: 'INVALID', 46 }); 47 } catch (e) { 48 error = e; 49 } 50 expect(error).not.toBeNull(); 51 }); 52 53 for (const encodingEntry of Object.entries(CryptoEncoding)) { 54 const [encodingKey, encoding] = encodingEntry; 55 describe(`Encoded with CryptoEncoding.${encodingKey}`, () => { 56 for (const entry of Object.entries(CryptoDigestAlgorithm)) { 57 const [key, algorithm] = entry; 58 it(`CryptoDigestAlgorithm.${key}`, async () => { 59 const targetValue = valueMapping[encoding][algorithm]; 60 if (supportedAlgorithm(algorithm)) { 61 const value = await Crypto.digestStringAsync(algorithm, testValue, { encoding }); 62 expect(value).toBe(targetValue); 63 } else { 64 let error = null; 65 try { 66 await Crypto.digestStringAsync(algorithm, testValue, { encoding }); 67 } catch (e) { 68 error = e; 69 } 70 expect(error).not.toBeNull(); 71 } 72 }); 73 } 74 }); 75 } 76 }); 77 }); 78} 79