Skip to content

improve encrypt // decrypt - add headers #119

@pagoru

Description

@pagoru

something like this

export const encryptSHA256 = async (
  text: string,
  key: string,
): Promise<string> => {
  const encoded = new TextEncoder().encode(text);
  const cryptoKey = await deriveKeySHA256(key);

  const iv = crypto.getRandomValues(new Uint8Array(12));
  const encrypted = new Uint8Array(
    await crypto.subtle.encrypt(
      { name: "AES-GCM", iv },
      cryptoKey,
      encoded,
    )
  );

  // [version(1)][iv(12)][ciphertext+tag]
  const payload = new Uint8Array(1 + iv.length + encrypted.length);
  payload[0] = 1; // version
  payload.set(iv, 1);
  payload.set(encrypted, 1 + iv.length);

  return base64Encode(payload);
};
export const decryptSHA256 = async (
  encryptedText: string,
  key: string,
): Promise<string | undefined> => {
  try {
    const data = base64Decode(encryptedText);

    // version(1) + iv(12) + tag(16 minimum)
    if (data.length < 29) return undefined;
    if (data[0] !== 1) return undefined;

    const iv = data.slice(1, 13);
    const encrypted = data.slice(13);

    const cryptoKey = await deriveKeySHA256(key);

    const decrypted = await crypto.subtle.decrypt(
      { name: "AES-GCM", iv },
      cryptoKey,
      encrypted,
    );

    return new TextDecoder().decode(decrypted);
  } catch {
    return undefined;
  }
};

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions