Skip to content
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
27 changes: 19 additions & 8 deletions packages/mask/background/services/crypto/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ import { encodeArrayBuffer, decodeText, decodeArrayBuffer, encodeText } from '@m
import type { AESCryptoKey } from '@masknet/shared-base'

// * Payload format: 🎶2/4|encrypted_comment:||
// * Payload format: 🎶3/4|iv|encrypted_comment:||
export async function encryptComment(
postIV: Uint8Array<ArrayBuffer>,
postContent: string,
comment: string,
): Promise<string> {
const key = await getCommentKey(postIV, postContent)
const commentIV = crypto.getRandomValues(new Uint8Array(16))

const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: postIV }, key, encodeText(comment))
return `\u{1F3B6}2/4|${encodeArrayBuffer(encrypted)}:||`
const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: commentIV }, key, encodeText(comment))
return `\u{1F3B6}3/4|${encodeArrayBuffer(commentIV)}|${encodeArrayBuffer(encrypted)}:||`
}
export async function decryptComment(
postIV: Uint8Array<ArrayBuffer>,
Expand All @@ -21,7 +23,11 @@ export async function decryptComment(
if (!payload) return null

const key = await getCommentKey(postIV, postContent)
const result = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: postIV }, key, decodeArrayBuffer(payload))
const result = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: payload[0] || postIV },
key,
decodeArrayBuffer(payload[1]),
)
return decodeText(result)
}

Expand All @@ -39,9 +45,14 @@ async function getCommentKey(postIV: Uint8Array<ArrayBuffer>, postContent: strin
)) as AESCryptoKey
}

function extractCommentPayload(text: string) {
const [_, toEnd] = text.split('\u{1F3B6}2/4|')
const [content, _2] = (toEnd || '').split(':||')
if (content.length) return content
return
function extractCommentPayload(text: string): [iv: undefined | Uint8Array<ArrayBuffer>, encrypted: string] | null {
const version2Header = text.indexOf('\u{1F3B6}3/4|')
const version1Header = text.indexOf('\u{1F3B6}2/4|')
if (version2Header === -1 && version1Header === -1) return null
const untilEnd = text.slice(version2Header !== -1 ? version2Header : version1Header).split(':||')
if (untilEnd.length === 0) return null
if (version1Header !== -1) return [undefined, untilEnd[0].slice('\u{1F3B6}2/4|'.length)]
const fields = untilEnd[0].split('|')
if (fields.length !== 3) return null
return [new Uint8Array(decodeArrayBuffer(fields[1])), fields[2]]
}
Loading