Class PkEncryption

java.lang.Object
io.github.fherbreteau.vodozemac.NativeHandle
io.github.fherbreteau.vodozemac.backup.PkEncryption
All Implemented Interfaces:
AutoCloseable

public final class PkEncryption extends NativeHandle
The encryption component of the PK Encryption module.

This implements the m.megolm_backup.v1.curve25519-aes-sha2 algorithm described in the Matrix specification. It is a hybrid encryption scheme utilizing Curve25519 and AES-CBC. X25519 ECDH is performed between an ephemeral key pair and a long-lived backup key pair to establish a shared secret, from which symmetric encryption and message authentication (MAC) keys are derived.

Warning: The algorithm contains a critical flaw and does not provide authentication of the ciphertext. The MAC is computed over an empty message rather than the actual ciphertext, meaning tampering with the ciphertext will not be detected.

A PkEncryption instance is created from the Curve25519 public key of a PkDecryption object and can be used to encrypt messages that only the corresponding PkDecryption can decrypt.

This class implements AutoCloseable and should be used in a try-with-resources block to ensure native resources are properly released.

Author:
François HERBRETEAU
See Also:
  • Method Details

    • fromKey

      public static PkEncryption fromKey(String key)
      Creates a PkEncryption instance from a base64-encoded Curve25519 public key.

      The public key should be obtained from an existing PkDecryption object via PkDecryption.publicKey().

      Parameters:
      key - the base64-encoded Curve25519 public key
      Returns:
      a new PkEncryption instance
      Throws:
      KeyException - if the key is not a valid Curve25519 public key
    • encrypt

      public PkMessage encrypt(byte[] plaintext)
      Encrypts the given plaintext and returns the encrypted message.

      The encryption uses an ephemeral Curve25519 key pair to perform ECDH with the recipient's public key. The resulting PkMessage contains the ciphertext, a MAC, and the ephemeral public key.

      Parameters:
      plaintext - the plaintext bytes to encrypt
      Returns:
      a PkMessage containing the encrypted message
      Throws:
      EncryptionException - if encryption fails (e.g. non-contributory key)