• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

opengovsg / formsg-javascript-sdk / 13652596553

04 Mar 2025 11:24AM UTC coverage: 97.495%. First build
13652596553

push

github

littlemight
fix: upgrade actions/cache

104 of 114 branches covered (91.23%)

Branch coverage included in aggregate %.

363 of 365 relevant lines covered (99.45%)

6.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

100.0
/src/crypto-base.ts
1
import nacl from 'tweetnacl'
3✔
2
import { decodeBase64, encodeBase64 } from 'tweetnacl-util'
3✔
3

4
import { generateKeypair } from './util/crypto'
3✔
5
import { EncryptedFileContent } from './types'
6

7
export default class CryptoBase {
12✔
8
  /**
9
   * Generates a new keypair for encryption.
10
   * @returns The generated keypair.
11
   */
12
  generate = generateKeypair
9✔
13

14
  /**
15
   * Encrypt given binary file with a unique keypair for each submission.
16
   * @param binary The file to encrypt, should be a blob that is converted to Uint8Array binary
17
   * @param publicKey The base-64 encoded public key
18
   * @returns Promise holding the encrypted file
19
   * @throws error if any of the encrypt methods fail
20
   */
21
  encryptFile = async (
9✔
22
    binary: Uint8Array,
23
    publicKey: string
7✔
24
  ): Promise<EncryptedFileContent> => {
25
    const fileKeypair = this.generate()
7✔
26
    const nonce = nacl.randomBytes(24)
7✔
27
    return {
7✔
28
      //! NOTE: submissionPublicKey here is a misnomer as a new keypair is generated per file.
29
      // The naming is only retained for backward-compatibility purposes.
30
      submissionPublicKey: fileKeypair.publicKey,
31
      nonce: encodeBase64(nonce),
32
      binary: nacl.box(
33
        binary,
34
        nonce,
35
        decodeBase64(publicKey),
36
        decodeBase64(fileKeypair.secretKey)
37
      ),
38
    }
39
  }
40

41
  /**
42
   * Decrypt the given encrypted file content.
43
   * @param secretKey Secret key as a base-64 string
44
   * @param encrypted Object returned from encryptFile function
45
   * @param encrypted.submissionPublicKey The file's public key as a base-64 string
46
   * @param encrypted.nonce The nonce as a base-64 string
47
   * @param encrypted.blob The encrypted file as a Blob object
48
   */
49
  decryptFile = async (
9✔
50
    secretKey: string,
51
    {
52
      submissionPublicKey: filePublicKey,
6✔
53
      nonce,
6✔
54
      binary: encryptedBinary,
6✔
55
    }: EncryptedFileContent
56
  ): Promise<Uint8Array | null> => {
57
    return nacl.box.open(
6✔
58
      encryptedBinary,
59
      decodeBase64(nonce),
60
      decodeBase64(filePublicKey),
61
      decodeBase64(secretKey)
62
    )
63
  }
64
}
3✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc