Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / library / e2ee-p2p / src / main / java / com / vayunmathur / e2ee / E2ee.kt

E2ee.kt41 lines · 1.9 KiBRaw
1package com.vayunmathur.e2ee
2
3import java.security.SecureRandom
4import javax.crypto.Cipher
5import javax.crypto.spec.GCMParameterSpec
6import javax.crypto.spec.SecretKeySpec
7
8/**
9 * Shared **symmetric** encryption primitives (AES-256-GCM), used across apps so content is always
10 * encrypted the same way: take a key from [newContentKey], then [aesEncrypt] / [aesDecrypt] with it.
11 *
12 * [Pqc] builds on this as well — `Pqc.encryptTo` / `Pqc.decrypt` AES-encrypt the payload under the
13 * ML-KEM shared secret. For asymmetric operations (encrypting to a peer, signatures, and the
14 * [SecurityCode] safety number) use [Pqc] and [PqcIdentity].
15 */
16object E2ee {
17 private const val GCM_TAG_BITS = 128
18 private const val IV_LEN = 12
19 private const val AES_KEY_BYTES = 32
20
21 /** A fresh random 256-bit content key. */
22 fun newContentKey(): ByteArray = ByteArray(AES_KEY_BYTES).also { SecureRandom().nextBytes(it) }
23
24 /** Encrypts [plaintext] with [key]; the random 12-byte IV is prepended to the ciphertext. */
25 fun aesEncrypt(key: ByteArray, plaintext: ByteArray): ByteArray {
26 val iv = ByteArray(IV_LEN).also { SecureRandom().nextBytes(it) }
27 val cipher = Cipher.getInstance("AES/GCM/NoPadding")
28 cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(GCM_TAG_BITS, iv))
29 return iv + cipher.doFinal(plaintext)
30 }
31
32 /** Decrypts data produced by [aesEncrypt] (IV prepended). */
33 fun aesDecrypt(key: ByteArray, data: ByteArray): ByteArray {
34 require(data.size >= IV_LEN) { "ciphertext too short: ${data.size}" }
35 val iv = data.copyOfRange(0, IV_LEN)
36 val ct = data.copyOfRange(IV_LEN, data.size)
37 val cipher = Cipher.getInstance("AES/GCM/NoPadding")
38 cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(GCM_TAG_BITS, iv))
39 return cipher.doFinal(ct)
40 }
41}