Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / e2ee-p2p / src / main / java / com / vayunmathur / e2ee / E2ee.kt
E2ee.kt40 lines · 1.8 KiBRaw
| 1 | package com.vayunmathur.e2ee |
| 2 | |
| 3 | import java.security.SecureRandom |
| 4 | import javax.crypto.Cipher |
| 5 | import javax.crypto.spec.GCMParameterSpec |
| 6 | import 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 | */ |
| 16 | object 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 | val iv = data.copyOfRange(0, IV_LEN) |
| 35 | val ct = data.copyOfRange(IV_LEN, data.size) |
| 36 | val cipher = Cipher.getInstance("AES/GCM/NoPadding") |
| 37 | cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(GCM_TAG_BITS, iv)) |
| 38 | return cipher.doFinal(ct) |
| 39 | } |
| 40 | } |