module Crypto.PubKey.Curve25519
( SecretKey
, PublicKey
, DhSecret
, dhSecret
, publicKey
, secretKey
, dh
, toPublic
) where
import Data.Word
import Foreign.Ptr
import GHC.Ptr
import Crypto.Internal.Compat
import Crypto.Internal.Imports
import Crypto.Internal.ByteArray (ByteArrayAccess, ScrubbedBytes, Bytes, withByteArray)
import qualified Crypto.Internal.ByteArray as B
newtype SecretKey = SecretKey ScrubbedBytes
deriving (Show,Eq,ByteArrayAccess,NFData)
newtype PublicKey = PublicKey Bytes
deriving (Show,Eq,ByteArrayAccess,NFData)
newtype DhSecret = DhSecret ScrubbedBytes
deriving (Show,Eq,ByteArrayAccess,NFData)
publicKey :: ByteArrayAccess bs => bs -> Either String PublicKey
publicKey bs
| B.length bs == 32 = Right $ PublicKey $ B.copyAndFreeze bs (\_ -> return ())
| otherwise = Left "invalid public key size"
secretKey :: ByteArrayAccess bs => bs -> Either String SecretKey
secretKey bs
| B.length bs == 32 = unsafeDoIO $ do
withByteArray bs $ \inp -> do
valid <- isValidPtr inp
if valid
then (Right . SecretKey) <$> B.copy bs (\_ -> return ())
else return $ Left "invalid secret key"
| otherwise = Left "secret key invalid size"
where
isValidPtr :: Ptr Word8 -> IO Bool
isValidPtr _ = do
return True
dhSecret :: ByteArrayAccess b => b -> Either String DhSecret
dhSecret bs
| B.length bs == 32 = Right $ DhSecret $ B.copyAndFreeze bs (\_ -> return ())
| otherwise = Left "invalid dh secret size"
dh :: PublicKey -> SecretKey -> DhSecret
dh (PublicKey pub) (SecretKey sec) = DhSecret <$>
B.allocAndFreeze 32 $ \result ->
withByteArray sec $ \psec ->
withByteArray pub $ \ppub ->
ccryptonite_curve25519 result psec ppub
toPublic :: SecretKey -> PublicKey
toPublic (SecretKey sec) = PublicKey <$>
B.allocAndFreeze 32 $ \result ->
withByteArray sec $ \psec ->
ccryptonite_curve25519 result psec basePoint
where
basePoint = Ptr "\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"#
foreign import ccall "cryptonite_curve25519_donna"
ccryptonite_curve25519 :: Ptr Word8
-> Ptr Word8
-> Ptr Word8
-> IO ()