{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}

module Crypto.HPKE.KEM (
    HPKEKEM (..),
    KEMAlg (..),
    encapEnv,
    decapEnv,
)
where

import Crypto.ECC (
    EllipticCurve (..),
    EllipticCurveDH (..),
 )
import Crypto.KEM (KEM (..))
import Crypto.Random (MonadRandom)

import Crypto.HPKE.PublicKey
import Crypto.HPKE.Types

----------------------------------------------------------------

-- | What HPKE needs of a KEM beyond what @crypton@'s 'KEM' class says.
--
-- RFC 9180 section 4.1 gives DHKEM four operations and the class has room
-- for two: @Encap@ is 'encapsulate', @Decap@ is 'decapsulate'.  @AuthEncap@
-- and @AuthDecap@ take a static sender key, which the class has no argument
-- for, so they are here.  They default to refusing, which is what a KEM
-- with no authenticated mode -- any post-quantum one -- should do.
--
-- The equalities pin the four associated types to the serialized forms of
-- section 4, which is what travels and what this package's entry points
-- take, so that 'Crypto.HPKE.setupS' can be written once for every KEM.
class
    ( KEM kem
    , EncapsulationKey kem ~ EncodedPublicKey
    , DecapsulationKey kem ~ EncodedSecretKey
    , Ciphertext kem ~ EncodedPublicKey
    , Coins kem ~ EncodedSecretKey
    ) =>
    HPKEKEM kem
    where
    -- | Draw what 'encapsulate' would have drawn, so that the
    -- authenticated forms can generate their ephemeral key the same way.
    --
    -- For every KEM here the coins are a secret key, so the default is to
    -- draw a key pair and keep the half that is one.
    generateCoins :: MonadRandom m => proxy kem -> m EncodedSecretKey
    generateCoins proxy kem
p = (EncodedPublicKey, EncodedSecretKey) -> EncodedSecretKey
forall a b. (a, b) -> b
snd ((EncodedPublicKey, EncodedSecretKey) -> EncodedSecretKey)
-> m (EncodedPublicKey, EncodedSecretKey) -> m EncodedSecretKey
forall a b. (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` proxy kem -> m (EncapsulationKey kem, DecapsulationKey kem)
forall kem (m :: * -> *) (proxy :: * -> *).
(KEM kem, MonadRandom m) =>
proxy kem -> m (EncapsulationKey kem, DecapsulationKey kem)
forall (m :: * -> *) (proxy :: * -> *).
MonadRandom m =>
proxy kem -> m (EncapsulationKey kem, DecapsulationKey kem)
generateKeyPair proxy kem
p

    -- | @AuthEncap@ of section 4.1, with the ephemeral key supplied.
    authEncapWith
        :: proxy kem
        -> EncodedSecretKey
        -- ^ @skS@, the sender's static key
        -> EncodedPublicKey
        -- ^ @pkR@
        -> EncodedSecretKey
        -- ^ @skE@
        -> Either HPKEError (EncodedPublicKey, SharedSecret)
    authEncapWith proxy kem
_ EncodedSecretKey
_ EncodedPublicKey
_ EncodedSecretKey
_ = HPKEError -> Either HPKEError (EncodedPublicKey, SharedSecret)
forall a b. a -> Either a b
Left (HPKEError -> Either HPKEError (EncodedPublicKey, SharedSecret))
-> HPKEError -> Either HPKEError (EncodedPublicKey, SharedSecret)
forall a b. (a -> b) -> a -> b
$ String -> HPKEError
Unsupported String
"authenticated mode"

    -- | @AuthDecap@ of section 4.1.  The sender is named by its public
    -- key: a receiver does not have the other side's secret key, and
    -- asking for one would be asking for the wrong thing.
    authDecap
        :: proxy kem
        -> EncodedPublicKey
        -- ^ @pkS@, the sender's static public key
        -> EncodedSecretKey
        -- ^ @skR@
        -> EncodedPublicKey
        -- ^ @enc@
        -> Either HPKEError SharedSecret
    authDecap proxy kem
_ EncodedPublicKey
_ EncodedSecretKey
_ EncodedPublicKey
_ = HPKEError -> Either HPKEError SharedSecret
forall a b. a -> Either a b
Left (HPKEError -> Either HPKEError SharedSecret)
-> HPKEError -> Either HPKEError SharedSecret
forall a b. (a -> b) -> a -> b
$ String -> HPKEError
Unsupported String
"authenticated mode"

    -- | The encapsulation key a decapsulation key belongs to.
    toEncapsulationKey
        :: proxy kem -> EncodedSecretKey -> Either HPKEError EncodedPublicKey

-- | A KEM that HPKE can run over, with its identity forgotten, for the
-- table that turns a @KEM_ID@ into one.
data KEMAlg = forall kem. HPKEKEM kem => KEMAlg (Proxy kem)

----------------------------------------------------------------

-- | @Encap@ and @AuthEncap@ of RFC 9180 section 4.1, with the ephemeral key
-- supplied.
--
-- Written out the same way 'decap' is: what it needs are the ephemeral key,
-- the sender's static key if the mode is authenticated, and the recipient's
-- public key.
encap
    :: (EllipticCurve group, EllipticCurveDH group)
    => Proxy group
    -> KeyDeriveFunction
    -> SecretKey group
    -> Maybe (SecretKey group)
    -> Encap
encap :: forall group.
(EllipticCurve group, EllipticCurveDH group) =>
Proxy group
-> KeyDeriveFunction
-> SecretKey group
-> Maybe (SecretKey group)
-> Encap
encap Proxy group
proxy KeyDeriveFunction
derive SecretKey group
skE Maybe (SecretKey group)
mskS enc0 :: EncodedPublicKey
enc0@(EncodedPublicKey ByteString
pkRm) = do
    pkR <- Proxy group -> EncodedPublicKey -> Either HPKEError (Point group)
forall group.
EllipticCurve group =>
Proxy group
-> EncodedPublicKey -> Either HPKEError (PublicKey group)
deserializePublicKey Proxy group
proxy EncodedPublicKey
enc0
    dh0 <- ecdh' proxy skE pkR $ EncapError "encap"
    (dh, pkSm) <- case mskS of
        Maybe (SecretKey group)
Nothing -> (SharedSecret, ByteString)
-> Either HPKEError (SharedSecret, ByteString)
forall a. a -> Either HPKEError a
forall (m :: * -> *) a. Monad m => a -> m a
return (SharedSecret
dh0, ByteString
"")
        Just SecretKey group
skS -> do
            let pkS :: Point group
pkS = Proxy group -> SecretKey group -> Point group
forall curve (proxy :: * -> *).
EllipticCurve curve =>
proxy curve -> Scalar curve -> Point curve
forall (proxy :: * -> *).
proxy group -> SecretKey group -> Point group
scalarToPoint Proxy group
proxy SecretKey group
skS
            dh1 <- Proxy group
-> SecretKey group
-> Point group
-> HPKEError
-> Either HPKEError SharedSecret
forall group a.
EllipticCurveDH group =>
Proxy group
-> SecretKey group -> PublicKey group -> a -> Either a SharedSecret
ecdh' Proxy group
proxy SecretKey group
skS Point group
pkR (HPKEError -> Either HPKEError SharedSecret)
-> HPKEError -> Either HPKEError SharedSecret
forall a b. (a -> b) -> a -> b
$ String -> HPKEError
EncapError String
"encap"
            let EncodedPublicKey pk = serializePublicKey proxy pkS
            return (dh0 <> dh1, pk)
    let pkE = Proxy group -> SecretKey group -> Point group
forall curve (proxy :: * -> *).
EllipticCurve curve =>
proxy curve -> Scalar curve -> Point curve
forall (proxy :: * -> *).
proxy group -> SecretKey group -> Point group
scalarToPoint Proxy group
proxy SecretKey group
skE
    let enc@(EncodedPublicKey pkEm) = serializePublicKey proxy pkE
        kem_context = ByteString
pkEm ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
pkRm ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
pkSm
        shared_secret = ScrubbedBytes -> SharedSecret
SharedSecret (ScrubbedBytes -> SharedSecret) -> ScrubbedBytes -> SharedSecret
forall a b. (a -> b) -> a -> b
$ ByteString -> ScrubbedBytes
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
convert (ByteString -> ScrubbedBytes) -> ByteString -> ScrubbedBytes
forall a b. (a -> b) -> a -> b
$ KeyDeriveFunction
derive SharedSecret
dh ByteString
kem_context
    return (shared_secret, enc)

encapEnv
    :: (EllipticCurve group, EllipticCurveDH group)
    => Proxy group
    -> KeyDeriveFunction
    -> EncodedSecretKey
    -> Maybe EncodedSecretKey
    -> Encap
encapEnv :: forall group.
(EllipticCurve group, EllipticCurveDH group) =>
Proxy group
-> KeyDeriveFunction
-> EncodedSecretKey
-> Maybe EncodedSecretKey
-> Encap
encapEnv Proxy group
proxy KeyDeriveFunction
derive EncodedSecretKey
skEm Maybe EncodedSecretKey
mskSm EncodedPublicKey
enc = do
    skE <- Proxy group -> EncodedSecretKey -> Either HPKEError (Scalar group)
forall group.
EllipticCurve group =>
Proxy group
-> EncodedSecretKey -> Either HPKEError (SecretKey group)
deserializeSecretKey Proxy group
proxy EncodedSecretKey
skEm
    mskS <- traverse (deserializeSecretKey proxy) mskSm
    encap proxy derive skE mskS enc

----------------------------------------------------------------

-- | @Decap@ and @AuthDecap@ of RFC 9180 section 4.1.
--
-- The sender is named by its public key, because that is all a receiver
-- has: @AuthDecap(enc, skR, pkS)@.
decap
    :: (EllipticCurve group, EllipticCurveDH group)
    => Proxy group
    -> KeyDeriveFunction
    -> SecretKey group
    -> Maybe (PublicKey group)
    -> Decap
decap :: forall group.
(EllipticCurve group, EllipticCurveDH group) =>
Proxy group
-> KeyDeriveFunction
-> SecretKey group
-> Maybe (PublicKey group)
-> EncodedPublicKey
-> Either HPKEError SharedSecret
decap Proxy group
proxy KeyDeriveFunction
derive SecretKey group
skR Maybe (PublicKey group)
mpkS enc :: EncodedPublicKey
enc@(EncodedPublicKey ByteString
pkEm) = do
    pkE <- Proxy group
-> EncodedPublicKey -> Either HPKEError (PublicKey group)
forall group.
EllipticCurve group =>
Proxy group
-> EncodedPublicKey -> Either HPKEError (PublicKey group)
deserializePublicKey Proxy group
proxy EncodedPublicKey
enc
    dh0 <- ecdh' proxy skR pkE $ DecapError "decap"
    (dh, pkSm) <- case mpkS of
        Maybe (PublicKey group)
Nothing -> (SharedSecret, ByteString)
-> Either HPKEError (SharedSecret, ByteString)
forall a. a -> Either HPKEError a
forall (m :: * -> *) a. Monad m => a -> m a
return (SharedSecret
dh0, ByteString
"")
        Just PublicKey group
pkS -> do
            dh1 <- Proxy group
-> SecretKey group
-> PublicKey group
-> HPKEError
-> Either HPKEError SharedSecret
forall group a.
EllipticCurveDH group =>
Proxy group
-> SecretKey group -> PublicKey group -> a -> Either a SharedSecret
ecdh' Proxy group
proxy SecretKey group
skR PublicKey group
pkS (HPKEError -> Either HPKEError SharedSecret)
-> HPKEError -> Either HPKEError SharedSecret
forall a b. (a -> b) -> a -> b
$ String -> HPKEError
DecapError String
"decap"
            let EncodedPublicKey pk = serializePublicKey proxy pkS
            return (dh0 <> dh1, pk)
    let pkR = Proxy group -> SecretKey group -> PublicKey group
forall curve (proxy :: * -> *).
EllipticCurve curve =>
proxy curve -> Scalar curve -> Point curve
forall (proxy :: * -> *).
proxy group -> SecretKey group -> PublicKey group
scalarToPoint Proxy group
proxy SecretKey group
skR
    let EncodedPublicKey pkRm = serializePublicKey proxy pkR
        kem_context = ByteString
pkEm ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
pkRm ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> ByteString
pkSm
        shared_secret = ScrubbedBytes -> SharedSecret
SharedSecret (ScrubbedBytes -> SharedSecret) -> ScrubbedBytes -> SharedSecret
forall a b. (a -> b) -> a -> b
$ ByteString -> ScrubbedBytes
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
convert (ByteString -> ScrubbedBytes) -> ByteString -> ScrubbedBytes
forall a b. (a -> b) -> a -> b
$ KeyDeriveFunction
derive SharedSecret
dh ByteString
kem_context
    return shared_secret

decapEnv
    :: (EllipticCurve group, EllipticCurveDH group)
    => Proxy group
    -> KeyDeriveFunction
    -> EncodedSecretKey
    -> Maybe EncodedPublicKey
    -> Decap
decapEnv :: forall group.
(EllipticCurve group, EllipticCurveDH group) =>
Proxy group
-> KeyDeriveFunction
-> EncodedSecretKey
-> Maybe EncodedPublicKey
-> EncodedPublicKey
-> Either HPKEError SharedSecret
decapEnv Proxy group
proxy KeyDeriveFunction
derive EncodedSecretKey
skRm Maybe EncodedPublicKey
mpkSm EncodedPublicKey
enc = do
    skR <- Proxy group -> EncodedSecretKey -> Either HPKEError (Scalar group)
forall group.
EllipticCurve group =>
Proxy group
-> EncodedSecretKey -> Either HPKEError (SecretKey group)
deserializeSecretKey Proxy group
proxy EncodedSecretKey
skRm
    mpkS <- traverse (deserializePublicKey proxy) mpkSm
    decap proxy derive skR mpkS enc

----------------------------------------------------------------

ecdh'
    :: EllipticCurveDH group
    => Proxy group
    -> SecretKey group
    -> PublicKey group
    -> a
    -> Either a SharedSecret
ecdh' :: forall group a.
EllipticCurveDH group =>
Proxy group
-> SecretKey group -> PublicKey group -> a -> Either a SharedSecret
ecdh' Proxy group
proxy SecretKey group
sk PublicKey group
pk a
err = case Proxy group
-> SecretKey group
-> PublicKey group
-> CryptoFailable SharedSecret
forall curve (proxy :: * -> *).
EllipticCurveDH curve =>
proxy curve
-> Scalar curve -> Point curve -> CryptoFailable SharedSecret
forall (proxy :: * -> *).
proxy group
-> SecretKey group
-> PublicKey group
-> CryptoFailable SharedSecret
ecdh Proxy group
proxy SecretKey group
sk PublicKey group
pk of
    CryptoPassed SharedSecret
a -> SharedSecret -> Either a SharedSecret
forall a b. b -> Either a b
Right SharedSecret
a
    CryptoFailed CryptoError
_ -> a -> Either a SharedSecret
forall a b. a -> Either a b
Left a
err