1import * as Crypto from 'expo-crypto'; 2import { Platform } from 'react-native'; 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 31const UNSUPPORTED = Platform.select({ 32 web: ['MD2', 'MD4', 'MD5'], 33 android: ['MD2', 'MD4'], 34 default: [], 35}); 36function supportedAlgorithm(algorithm) { 37 return !UNSUPPORTED.includes(algorithm); 38} 39 40export async function test({ describe, it, expect }) { 41 describe('Crypto', () => { 42 describe('digestStringAsync()', async () => { 43 it(`Invalid CryptoEncoding throws an error`, async () => { 44 let error = null; 45 try { 46 await Crypto.digestStringAsync(CryptoDigestAlgorithm.SHA1, testValue, { 47 encoding: 'INVALID', 48 }); 49 } catch (e) { 50 error = e; 51 } 52 expect(error).not.toBeNull(); 53 }); 54 55 for (const encodingEntry of Object.entries(CryptoEncoding)) { 56 const [encodingKey, encoding] = encodingEntry; 57 describe(`Encoded with CryptoEncoding.${encodingKey}`, () => { 58 for (const entry of Object.entries(CryptoDigestAlgorithm)) { 59 const [key, algorithm] = entry; 60 it(`CryptoDigestAlgorithm.${key}`, async () => { 61 const targetValue = valueMapping[encoding][algorithm]; 62 if (supportedAlgorithm(algorithm)) { 63 const value = await Crypto.digestStringAsync(algorithm, testValue, { encoding }); 64 expect(value).toBe(targetValue); 65 } else { 66 let error = null; 67 try { 68 await Crypto.digestStringAsync(algorithm, testValue, { encoding }); 69 } catch (e) { 70 error = e; 71 } 72 expect(error).not.toBeNull(); 73 } 74 }); 75 } 76 }); 77 } 78 }); 79 }); 80} 81