Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: expose explicit decrypt of remote attachments #146

Merged
merged 1 commit into from
Aug 22, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 22 additions & 16 deletions Sources/XMTP/Codecs/RemoteAttachmentCodec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,31 +93,37 @@ public struct RemoteAttachment {
)
}

public func content() async throws -> EncodedContent {
let payload = try await fetcher.fetch(url)

if payload.isEmpty {
throw RemoteAttachmentError.payloadNotFound
public static func decryptEncoded(encrypted: EncryptedEncodedContent) throws -> EncodedContent {
if RemoteAttachment.sha256(data: encrypted.payload) != encrypted.digest {
throw RemoteAttachmentError.invalidDigest("content digest does not match. expected: \(encrypted.digest), got: \(SHA256.hash(data: encrypted.payload).description)")
}

let ciphertext = CipherText.with {
let decrypted = try Crypto.decrypt(encrypted.secret, CipherText.with {
let aes256GcmHkdfSha256 = CipherText.Aes256gcmHkdfsha256.with { aes in
aes.hkdfSalt = salt
aes.gcmNonce = nonce
aes.payload = payload
aes.hkdfSalt = encrypted.salt
aes.gcmNonce = encrypted.nonce
aes.payload = encrypted.payload
}

$0.aes256GcmHkdfSha256 = aes256GcmHkdfSha256
}
})
return try EncodedContent(serializedData: decrypted)
}

if RemoteAttachment.sha256(data: payload) != contentDigest {
throw RemoteAttachmentError.invalidDigest("content digest does not match. expected: \(contentDigest), got: \(SHA256.hash(data: payload).description)")
}
public func content() async throws -> EncodedContent {
let payload = try await fetcher.fetch(url)

let decryptedPayloadData = try Crypto.decrypt(secret, ciphertext)
let decryptedPayload = try EncodedContent(serializedData: decryptedPayloadData)
if payload.isEmpty {
throw RemoteAttachmentError.payloadNotFound
}

return decryptedPayload
return try RemoteAttachment.decryptEncoded(encrypted: EncryptedEncodedContent(
secret: secret,
digest: contentDigest,
salt: salt,
nonce: nonce,
payload: payload
))
}

private static func sha256(data: Data) -> String {
Expand Down