Changeset View
Changeset View
Standalone View
Standalone View
native/expo-modules/aes-crypto/ios/AESCryptoModule.swift
import ExpoModulesCore | import ExpoModulesCore | ||||
import CryptoKit | |||||
public class AESCryptoModule: Module { | public class AESCryptoModule: Module { | ||||
public func definition() -> ModuleDefinition { | public func definition() -> ModuleDefinition { | ||||
Name("AESCrypto") | Name("AESCrypto") | ||||
Function("hello") { () -> String in | Function("generateKey", generateKey) | ||||
return "Hello world! 👋" | |||||
} | } | ||||
} | } | ||||
// MARK: - Function implementations | |||||
private func generateKey(destination: Uint8Array) throws { | |||||
let key = SymmetricKey(size: .bits256) | |||||
guard destination.byteLength * 8 == key.bitCount else { | |||||
throw InvalidKeyLengthException() | |||||
} | |||||
atul: Before we even generate `key` via `SymmetricKey`, should we check that `destination.byteLength`… | |||||
bartekAuthorUnsubmitted Done Inline ActionsThe only reason the guard is below SymmetricKey is that I wanted to use its bitCount property to get the desired destination length, but you're right that it can be done this way: guard destination.byteLength == KEY_SIZE else { throw InvalidKeyLengthException() } let key = SymmetricKey(size: .bits256) I'll refactor this as it is more clear solution bartek: The only reason the guard is below `SymmetricKey` is that I wanted to use its `bitCount`… | |||||
key.withUnsafeBytes { bytes in | |||||
let _ = bytes.copyBytes(to: destination.rawBufferPtr()) | |||||
} | |||||
} | |||||
// MARK: - Utilities | |||||
extension TypedArray { | |||||
func rawBufferPtr() -> UnsafeMutableRawBufferPointer { | |||||
UnsafeMutableRawBufferPointer(start: self.rawPointer, | |||||
count: self.byteLength) | |||||
} | |||||
} | |||||
// MARK: - Exception definitions | |||||
private class InvalidKeyLengthException: Exception { | |||||
override var reason: String { | |||||
"The AES key has invalid length" | |||||
} | |||||
} | } |
Before we even generate key via SymmetricKey, should we check that destination.byteLength is 32 and throw InvalidDestinationSizeException() if not?
It seems like destination is the input that we want to validate, so we should just do that directly? It's not really so much that SymmetricKey is giving us incorrect size key since it's (I'm assuming) always going to give us exactly the size we're asking for?
Feel free to re-request review if there's something I'm missing here.