packages feed

crypton-x509 1.10.3 → 1.11.0

raw patch · 10 files changed

+1340/−283 lines, 10 filesdep ~cryptonPVP ok

version bump matches the API change (PVP)

Dependency ranges changed: crypton

API changes (from Hackage documentation)

- Data.X509: DistinguishedName :: [(OID, ASN1CharacterString)] -> DistinguishedName
- Data.X509: DistributionNameRelative :: DistinguishedName -> DistributionPoint
- Data.X509: ExtAuthorityKeyId :: ByteString -> ExtAuthorityKeyId
- Data.X509: MLDSAKeyBoth :: MLDSAKeyForm
- Data.X509: MLDSAKeyExpanded :: MLDSAKeyForm
- Data.X509: MLDSAKeySeed :: MLDSAKeyForm
- Data.X509: [getDistinguishedElements] :: DistinguishedName -> [(OID, ASN1CharacterString)]
- Data.X509: data MLDSAKeyForm
- Data.X509: newtype DistinguishedName
+ Data.X509: AltNameEDIParty :: ByteString -> AltName
+ Data.X509: AltNameOther :: OID -> ByteString -> AltName
+ Data.X509: AltNameRegisteredID :: OID -> AltName
+ Data.X509: AltNameX400 :: ByteString -> AltName
+ Data.X509: DistributionPointRelativeName :: RelativeDistinguishedName -> DistributionPointName
+ Data.X509: DnDomainComponent :: DnElement
+ Data.X509: DnGenerationQualifier :: DnElement
+ Data.X509: DnGivenName :: DnElement
+ Data.X509: DnInitials :: DnElement
+ Data.X509: DnLocality :: DnElement
+ Data.X509: DnName :: DnElement
+ Data.X509: DnPostalCode :: DnElement
+ Data.X509: DnPseudonym :: DnElement
+ Data.X509: DnQualifier :: DnElement
+ Data.X509: DnSerialNumber :: DnElement
+ Data.X509: DnStateOrProvince :: DnElement
+ Data.X509: DnStreetAddress :: DnElement
+ Data.X509: DnSurname :: DnElement
+ Data.X509: DnTitle :: DnElement
+ Data.X509: DnUserId :: DnElement
+ Data.X509: HashSHA3_224 :: HashALG
+ Data.X509: HashSHA3_256 :: HashALG
+ Data.X509: HashSHA3_384 :: HashALG
+ Data.X509: HashSHA3_512 :: HashALG
+ Data.X509: MLKeyBoth :: MLKeyForm
+ Data.X509: MLKeyExpanded :: MLKeyForm
+ Data.X509: MLKeySeed :: MLKeyForm
+ Data.X509: PrivKeyMLKEM1024 :: PrivKeyMLKEM MLKEM1024 -> PrivKey
+ Data.X509: PrivKeyMLKEM512 :: PrivKeyMLKEM MLKEM512 -> PrivKey
+ Data.X509: PrivKeyMLKEM768 :: PrivKeyMLKEM MLKEM768 -> PrivKey
+ Data.X509: PrivKeyRSAPSS :: PrivateKey -> Maybe PSSParams -> PrivKey
+ Data.X509: PubKeyALG_MLKEM1024 :: PubKeyALG
+ Data.X509: PubKeyALG_MLKEM512 :: PubKeyALG
+ Data.X509: PubKeyALG_MLKEM768 :: PubKeyALG
+ Data.X509: PubKeyMLKEM1024 :: EncapsulationKey MLKEM1024 -> PubKey
+ Data.X509: PubKeyMLKEM512 :: EncapsulationKey MLKEM512 -> PubKey
+ Data.X509: PubKeyMLKEM768 :: EncapsulationKey MLKEM768 -> PubKey
+ Data.X509: PubKeyRSAPSS :: PublicKey -> Maybe PSSParams -> PubKey
+ Data.X509: SignatureALG_RSAPSS :: PSSParams -> SignatureALG
+ Data.X509: data DistinguishedName
+ Data.X509: data DistributionPointName
+ Data.X509: data MLKeyForm
+ Data.X509: data PSSParams
+ Data.X509: data PrivKeyMLKEM p
+ Data.X509: data PubKeyDH
+ Data.X509: defaultDistributionPoint :: DistributionPoint
+ Data.X509: defaultExtAuthorityKeyId :: ExtAuthorityKeyId
+ Data.X509: defaultPSSParams :: HashALG -> PSSParams
+ Data.X509: dhPublicKey :: Integer -> Integer -> Integer -> Integer -> PubKeyDH
+ Data.X509: fromRDNs :: [RelativeDistinguishedName] -> DistinguishedName
+ Data.X509: getRDNs :: DistinguishedName -> [RelativeDistinguishedName]
+ Data.X509: pattern DistinguishedName :: [(OID, ASN1CharacterString)] -> DistinguishedName
+ Data.X509: pattern ExtAuthorityKeyId :: ByteString -> ExtAuthorityKeyId
+ Data.X509: pattern MLDSAKeyBoth :: MLKeyForm
+ Data.X509: pattern MLDSAKeyExpanded :: MLKeyForm
+ Data.X509: pattern MLDSAKeySeed :: MLKeyForm
+ Data.X509: privkeyMLKEMFromKey :: DecapsulationKey p -> PrivKeyMLKEM p
+ Data.X509: privkeyMLKEMFromSeed :: (MLKEM p, ByteArrayAccess ba) => proxy p -> MLKeyForm -> ba -> CryptoFailable (PrivKeyMLKEM p)
+ Data.X509: privkeyMLKEM_form :: PrivKeyMLKEM p -> MLKeyForm
+ Data.X509: privkeyMLKEM_key :: PrivKeyMLKEM p -> DecapsulationKey p
+ Data.X509: privkeyMLKEM_seed :: PrivKeyMLKEM p -> Maybe ScrubbedBytes
+ Data.X509: pubkeyDH_g :: PubKeyDH -> Integer
+ Data.X509: pubkeyDH_j :: PubKeyDH -> Maybe Integer
+ Data.X509: pubkeyDH_p :: PubKeyDH -> Integer
+ Data.X509: pubkeyDH_q :: PubKeyDH -> Integer
+ Data.X509: pubkeyDH_validation :: PubKeyDH -> Maybe (BitArray, Integer)
+ Data.X509: pubkeyDH_y :: PubKeyDH -> Integer
+ Data.X509: rsaPSSSignatureALG :: PSSParams -> SignatureALG
+ Data.X509: signatureALGPSSParams :: SignatureALG -> Maybe PSSParams
+ Data.X509: type MLDSAKeyForm = MLKeyForm
+ Data.X509: type RelativeDistinguishedName = [(OID, ASN1CharacterString)]
- Data.X509: DistributionPointFullName :: [AltName] -> DistributionPoint
+ Data.X509: DistributionPointFullName :: [AltName] -> DistributionPointName
- Data.X509: PubKeyDH :: (Integer, Integer, Integer, Maybe Integer, ([Word8], Integer)) -> PubKey
+ Data.X509: PubKeyDH :: PubKeyDH -> PubKey
- Data.X509: privkeyMLDSAFromSeed :: (MLDSA p, ByteArrayAccess ba) => proxy p -> MLDSAKeyForm -> ba -> CryptoFailable (PrivKeyMLDSA p)
+ Data.X509: privkeyMLDSAFromSeed :: (MLDSA p, ByteArrayAccess ba) => proxy p -> MLKeyForm -> ba -> CryptoFailable (PrivKeyMLDSA p)
- Data.X509: privkeyMLDSA_form :: PrivKeyMLDSA p -> MLDSAKeyForm
+ Data.X509: privkeyMLDSA_form :: PrivKeyMLDSA p -> MLKeyForm

Files

ChangeLog.md view
@@ -1,5 +1,38 @@ # ChangeLog for crypton-x509 +## 1.11.0++Certificates are represented without losing information: RSA-PSS+parameters, multi-valued RDNs, all GeneralName forms and all fields of+AuthorityKeyIdentifier and DistributionPoint are kept.  Constructors of+types that may grow are hidden; use the `default...` values with record+update syntax.  `DistinguishedName`, `ExtAuthorityKeyId` and+`MLDSAKeyForm` (now `MLKeyForm`) keep working through pattern synonyms.+X9.42 DH, RSASSA-PSS and ML-KEM keys and SHA-3 signatures are supported.++* Keep RSA-PSS parameters+  [#53](https://github.com/kazu-yamamoto/crypton-certificate/pull/53)+* Keep multi-valued RDNs+  [#54](https://github.com/kazu-yamamoto/crypton-certificate/pull/54)+* Represent X9.42 DH public keys+  [#55](https://github.com/kazu-yamamoto/crypton-certificate/pull/55)+* Keep all GeneralName forms+  [#57](https://github.com/kazu-yamamoto/crypton-certificate/pull/57)+* Keep all fields of AuthorityKeyIdentifier+  [#58](https://github.com/kazu-yamamoto/crypton-certificate/pull/58)+* Keep all fields of DistributionPoint+  [#59](https://github.com/kazu-yamamoto/crypton-certificate/pull/59)+* Add more DnElement attributes+  [#60](https://github.com/kazu-yamamoto/crypton-certificate/pull/60)+* Support RSASSA-PSS keys+  [#61](https://github.com/kazu-yamamoto/crypton-certificate/pull/61)+* Support SHA-3 signature algorithms+  [#62](https://github.com/kazu-yamamoto/crypton-certificate/pull/62)+* Support ML-KEM keys+  [#63](https://github.com/kazu-yamamoto/crypton-certificate/pull/63)+* Encode NULL parameters for RSA with SHA-3+  [#64](https://github.com/kazu-yamamoto/crypton-certificate/pull/64)+ ## 1.10.3  Parsing is stricter: certificates with data after the public key,
Data/X509.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE PatternSynonyms #-}+ -- | -- Module      : Data.X509 -- License     : BSD-style@@ -15,16 +17,34 @@     Certificate (..),     PubKey (..),     PubKeyEC (..),+    PubKeyDH,+    dhPublicKey,+    pubkeyDH_p,+    pubkeyDH_g,+    pubkeyDH_q,+    pubkeyDH_j,+    pubkeyDH_validation,+    pubkeyDH_y,     SerializedPoint (..),     PrivKey (..),     PrivKeyEC (..),     PrivKeyMLDSA,-    MLDSAKeyForm (..),+    MLKeyForm (..),+    MLDSAKeyForm,+    pattern MLDSAKeySeed,+    pattern MLDSAKeyExpanded,+    pattern MLDSAKeyBoth,     privkeyMLDSAFromSeed,     privkeyMLDSAFromKey,     privkeyMLDSA_key,     privkeyMLDSA_seed,     privkeyMLDSA_form,+    PrivKeyMLKEM,+    privkeyMLKEMFromSeed,+    privkeyMLKEMFromKey,+    privkeyMLKEM_key,+    privkeyMLKEM_seed,+    privkeyMLKEM_form,     pubkeyToAlg,     privkeyToAlg,     module Data.X509.AlgorithmIdentifier,@@ -35,7 +55,10 @@     module Data.X509.CRL,      -- * Naming-    DistinguishedName (..),+    DistinguishedName (DistinguishedName, getDistinguishedElements),+    RelativeDistinguishedName,+    getRDNs,+    fromRDNs,     DnElement (..),     ASN1CharacterString (..),     getDnElement,@@ -73,7 +96,7 @@ import qualified Data.ByteArray as BA import qualified Data.ByteString as B -import Data.X509.AlgorithmIdentifier+import Data.X509.AlgorithmIdentifier hiding (pssKeyAlgToASN1, pssKeyParamsFromASN1) import Data.X509.CRL import Data.X509.Cert import Data.X509.CertificateChain@@ -121,7 +144,7 @@         . DistinguishedNameInner         . dnLowerUTF8   where-    dnLowerUTF8 (DistinguishedName l) = DistinguishedName $ map (second toLowerUTF8) l+    dnLowerUTF8 = fromRDNs . map (map (second toLowerUTF8)) . getRDNs     toLowerUTF8 (ASN1CharacterString _ s) = ASN1CharacterString UTF8 (B.map asciiToLower s)     asciiToLower c         | c >= w8A && c <= w8Z =
Data/X509/AlgorithmIdentifier.hs view
@@ -8,6 +8,17 @@     HashALG (..),     PubKeyALG (..),     SignatureALG (..),+    PSSParams,+    pssHash,+    pssMGFHash,+    pssSaltLength,+    defaultPSSParams,+    rsaPSSSignatureALG,+    signatureALGPSSParams,++    -- * Internal+    pssKeyParamsFromASN1,+    pssKeyAlgToASN1, ) where  import Data.ASN1.Types@@ -22,6 +33,10 @@     | HashSHA256     | HashSHA384     | HashSHA512+    | HashSHA3_224+    | HashSHA3_256+    | HashSHA3_384+    | HashSHA3_512     deriving (Show, Eq)  -- | Public Key Algorithm@@ -48,6 +63,12 @@       PubKeyALG_MLDSA65     | -- | ML-DSA-87 signature algorithm (RFC 9881)       PubKeyALG_MLDSA87+    | -- | ML-KEM-512 key encapsulation (RFC 9935)+      PubKeyALG_MLKEM512+    | -- | ML-KEM-768 key encapsulation (RFC 9935)+      PubKeyALG_MLKEM768+    | -- | ML-KEM-1024 key encapsulation (RFC 9935)+      PubKeyALG_MLKEM1024     | -- | Diffie Hellman Public Key algorithm       PubKeyALG_DH     | -- | Unknown Public Key algorithm@@ -61,8 +82,57 @@     = SignatureALG HashALG PubKeyALG     | SignatureALG_IntrinsicHash PubKeyALG     | SignatureALG_Unknown OID+    | -- | RSASSA-PSS with parameters other than 'defaultPSSParams'.  With the+      -- default parameters, @SignatureALG h PubKeyALG_RSAPSS@ is used instead;+      -- 'rsaPSSSignatureALG' picks the right form.+      SignatureALG_RSAPSS PSSParams     deriving (Show, Eq) +-- | RSASSA-PSS parameters (RFC 4055).  Only MGF1 and the trailer field 1+-- are supported.  The constructor is hidden; use 'defaultPSSParams' and+-- record update syntax.+data PSSParams = PSSParams+    { pssHash :: HashALG+    -- ^ The message hash+    , pssMGFHash :: HashALG+    -- ^ The hash used by MGF1+    , pssSaltLength :: Int+    -- ^ The salt length in bytes+    }+    deriving (Show, Eq)++-- | The hash for both the message and MGF1, and the salt length equal to+-- the hash length.+defaultPSSParams :: HashALG -> PSSParams+defaultPSSParams h = PSSParams h h (hashLength h)++hashLength :: HashALG -> Int+hashLength HashMD2 = 16+hashLength HashMD5 = 16+hashLength HashSHA1 = 20+hashLength HashSHA224 = 28+hashLength HashSHA256 = 32+hashLength HashSHA384 = 48+hashLength HashSHA512 = 64+hashLength HashSHA3_224 = 28+hashLength HashSHA3_256 = 32+hashLength HashSHA3_384 = 48+hashLength HashSHA3_512 = 64++-- | The RSASSA-PSS signature algorithm with the given parameters.+rsaPSSSignatureALG :: PSSParams -> SignatureALG+rsaPSSSignatureALG p+    | p == defaultPSSParams h = SignatureALG h PubKeyALG_RSAPSS+    | otherwise = SignatureALG_RSAPSS p+  where+    h = pssHash p++-- | The RSASSA-PSS parameters of a signature algorithm, if any.+signatureALGPSSParams :: SignatureALG -> Maybe PSSParams+signatureALGPSSParams (SignatureALG h PubKeyALG_RSAPSS) = Just (defaultPSSParams h)+signatureALGPSSParams (SignatureALG_RSAPSS p) = Just p+signatureALGPSSParams _ = Nothing+ instance OIDable PubKeyALG where     getObjectID PubKeyALG_RSA = [1, 2, 840, 113549, 1, 1, 1]     getObjectID PubKeyALG_RSAPSS = [1, 2, 840, 113549, 1, 1, 10]@@ -75,6 +145,9 @@     getObjectID PubKeyALG_MLDSA44 = [2, 16, 840, 1, 101, 3, 4, 3, 17]     getObjectID PubKeyALG_MLDSA65 = [2, 16, 840, 1, 101, 3, 4, 3, 18]     getObjectID PubKeyALG_MLDSA87 = [2, 16, 840, 1, 101, 3, 4, 3, 19]+    getObjectID PubKeyALG_MLKEM512 = [2, 16, 840, 1, 101, 3, 4, 4, 1]+    getObjectID PubKeyALG_MLKEM768 = [2, 16, 840, 1, 101, 3, 4, 4, 2]+    getObjectID PubKeyALG_MLKEM1024 = [2, 16, 840, 1, 101, 3, 4, 4, 3]     getObjectID PubKeyALG_DH = [1, 2, 840, 10046, 2, 1]     getObjectID (PubKeyALG_Unknown oid) = oid @@ -95,6 +168,18 @@     , ([1, 2, 840, 10045, 4, 3, 4], SignatureALG HashSHA512 PubKeyALG_EC)     , ([2, 16, 840, 1, 101, 3, 4, 3, 1], SignatureALG HashSHA224 PubKeyALG_DSA)     , ([2, 16, 840, 1, 101, 3, 4, 3, 2], SignatureALG HashSHA256 PubKeyALG_DSA)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 5], SignatureALG HashSHA3_224 PubKeyALG_DSA)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 6], SignatureALG HashSHA3_256 PubKeyALG_DSA)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 7], SignatureALG HashSHA3_384 PubKeyALG_DSA)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 8], SignatureALG HashSHA3_512 PubKeyALG_DSA)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 9], SignatureALG HashSHA3_224 PubKeyALG_EC)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 10], SignatureALG HashSHA3_256 PubKeyALG_EC)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 11], SignatureALG HashSHA3_384 PubKeyALG_EC)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 12], SignatureALG HashSHA3_512 PubKeyALG_EC)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 13], SignatureALG HashSHA3_224 PubKeyALG_RSA)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 14], SignatureALG HashSHA3_256 PubKeyALG_RSA)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 15], SignatureALG HashSHA3_384 PubKeyALG_RSA)+    , ([2, 16, 840, 1, 101, 3, 4, 3, 16], SignatureALG HashSHA3_512 PubKeyALG_RSA)     , ([1, 3, 101, 112], SignatureALG_IntrinsicHash PubKeyALG_Ed25519)     , ([1, 3, 101, 113], SignatureALG_IntrinsicHash PubKeyALG_Ed448)     ,@@ -114,10 +199,15 @@ -- | Hash algorithms in RSASSA-PSS parameters. pssHashTable :: [(OID, HashALG)] pssHashTable =-    [ ([2, 16, 840, 1, 101, 3, 4, 2, 1], HashSHA256)+    [ ([1, 3, 14, 3, 2, 26], HashSHA1)+    , ([2, 16, 840, 1, 101, 3, 4, 2, 1], HashSHA256)     , ([2, 16, 840, 1, 101, 3, 4, 2, 2], HashSHA384)     , ([2, 16, 840, 1, 101, 3, 4, 2, 3], HashSHA512)     , ([2, 16, 840, 1, 101, 3, 4, 2, 4], HashSHA224)+    , ([2, 16, 840, 1, 101, 3, 4, 2, 7], HashSHA3_224)+    , ([2, 16, 840, 1, 101, 3, 4, 2, 8], HashSHA3_256)+    , ([2, 16, 840, 1, 101, 3, 4, 2, 9], HashSHA3_384)+    , ([2, 16, 840, 1, 101, 3, 4, 2, 10], HashSHA3_512)     ]  pssHashOID :: HashALG -> OID@@ -134,19 +224,89 @@     maybe (error ("unknown OID for " ++ show sig)) fst $         find ((==) sig . snd) sig_table --- | PSS salt length. Always assume ``-sigopt rsa_pss_saltlen:-1``-saltLen :: HashALG -> Integer-saltLen HashSHA256 = 32-saltLen HashSHA384 = 48-saltLen HashSHA512 = 64-saltLen HashSHA224 = 28-saltLen _ = error "toASN1: X509.SignatureAlg.HashAlg: Unknown hash"+oidRSAPSS, oidMGF1 :: OID+oidRSAPSS = [1, 2, 840, 113549, 1, 1, 10]+oidMGF1 = [1, 2, 840, 113549, 1, 1, 8] -pss :: OID -> [ASN1] -> Either String (SignatureALG, [ASN1])-pss hash xs = case lookup hash pssHashTable of-    Just h -> Right (SignatureALG h PubKeyALG_RSAPSS, xs)-    Nothing -> Left ("fromASN1: X509.SignatureALG: unknown PSS hash " ++ show hash)+-- | Parse the contents of RSASSA-PSS-params, after its 'Start' 'Sequence'.+parsePSSParams :: [ASN1] -> Either String (PSSParams, [ASN1])+parsePSSParams xs0 = do+    (h, xs1) <- field 0 hashAlg HashSHA1 xs0+    (m, xs2) <- field 1 mgf HashSHA1 xs1+    (s, xs3) <- field 2 int 20 xs2+    (t, xs4) <- field 3 int 1 xs3+    case xs4 of+        End Sequence : rest+            | t == (1 :: Int) -> Right (PSSParams h m s, rest)+        _ -> Left "fromASN1: X509.SignatureALG: invalid PSS parameters"+  where+    field n p _ (Start (Container Context n') : xs)+        | n == n' = do+            (v, ys) <- p xs+            case ys of+                End (Container Context n'') : zs | n'' == n -> Right (v, zs)+                _ -> Left "fromASN1: X509.SignatureALG: invalid PSS parameters"+    field _ _ def xs = Right (def, xs)+    hashAlg (Start Sequence : OID o : Null : End Sequence : xs) = hashOID o xs+    hashAlg (Start Sequence : OID o : End Sequence : xs) = hashOID o xs+    hashAlg _ = Left "fromASN1: X509.SignatureALG: invalid PSS hash"+    hashOID o xs = case lookup o pssHashTable of+        Just h -> Right (h, xs)+        Nothing -> Left ("fromASN1: X509.SignatureALG: unknown PSS hash " ++ show o)+    mgf (Start Sequence : OID o : xs)+        | o == oidMGF1 = do+            (h, ys) <- hashAlg xs+            case ys of+                End Sequence : zs -> Right (h, zs)+                _ -> Left "fromASN1: X509.SignatureALG: invalid MGF1"+    mgf _ = Left "fromASN1: X509.SignatureALG: unsupported mask generation function"+    int (IntVal i : xs)+        | i >= 0 && i <= 65536 = Right (fromIntegral i, xs)+    int _ = Left "fromASN1: X509.SignatureALG: invalid PSS integer" +-- | Encode an AlgorithmIdentifier of RSASSA-PSS with its parameters,+-- omitting the DER default values.  Hash identifiers have NULL+-- parameters as in RFC 4055 2.1.+encodePSSParams :: PSSParams -> [ASN1] -> [ASN1]+encodePSSParams p xs =+    Start Sequence : OID oidRSAPSS : pssParamsToASN1 p (End Sequence : xs)++pssParamsToASN1 :: PSSParams -> [ASN1] -> [ASN1]+pssParamsToASN1 (PSSParams h m s) xs =+    Start Sequence : (hashField ++ mgfField ++ saltField ++ End Sequence : xs)+  where+    hashField+        | h == HashSHA1 = []+        | otherwise = ctx 0 [Start Sequence, OID (pssHashOID h), Null, End Sequence]+    mgfField+        | m == HashSHA1 = []+        | otherwise =+            ctx 1 $+                [Start Sequence, OID oidMGF1, Start Sequence, OID (pssHashOID m), Null]+                    ++ [End Sequence, End Sequence]+    saltField+        | s == 20 = []+        | otherwise = ctx 2 [IntVal (fromIntegral s)]+    ctx n l = Start (Container Context n) : l ++ [End (Container Context n)]++-- | Parse the rest of an RSASSA-PSS key AlgorithmIdentifier, after its+-- OID, up to and including its 'End' 'Sequence'.  Absent parameters+-- (RFC 4055 1.2) mean that the key is not restricted.+pssKeyParamsFromASN1 :: [ASN1] -> Either String (Maybe PSSParams, [ASN1])+pssKeyParamsFromASN1 (End Sequence : xs) = Right (Nothing, xs)+pssKeyParamsFromASN1 (Null : End Sequence : xs) = Right (Nothing, xs)+pssKeyParamsFromASN1 (Start Sequence : xs) = do+    (p, ys) <- parsePSSParams xs+    case ys of+        End Sequence : zs -> Right (Just p, zs)+        _ -> Left "fromASN1: RSASSA-PSS key: invalid parameters"+pssKeyParamsFromASN1 _ = Left "fromASN1: RSASSA-PSS key: invalid parameters"++-- | Encode an AlgorithmIdentifier of an RSASSA-PSS key.+pssKeyAlgToASN1 :: Maybe PSSParams -> [ASN1] -> [ASN1]+pssKeyAlgToASN1 mp xs =+    Start Sequence : OID oidRSAPSS : maybe id pssParamsToASN1 mp (End Sequence : xs)+ instance ASN1Object SignatureALG where     fromASN1 (Start Sequence : OID oid : Null : End Sequence : xs) =         case oidSig oid of@@ -155,101 +315,17 @@             signatureAlg -> Right (signatureAlg, xs)     fromASN1 (Start Sequence : OID oid : End Sequence : xs) =         Right (oidSig oid, xs)-    fromASN1-        ( Start Sequence-                : OID [1, 2, 840, 113549, 1, 1, 10]-                : Start Sequence-                : Start (Container Context 0)-                : Start Sequence-                : OID hash1-                : End Sequence-                : End (Container Context 0)-                : Start (Container Context 1)-                : Start Sequence-                : OID [1, 2, 840, 113549, 1, 1, 8]-                : Start Sequence-                : OID _hash2-                : End Sequence-                : End Sequence-                : End (Container Context 1)-                : Start (Container Context 2)-                : IntVal _iv-                : End (Container Context 2)-                : End Sequence-                : End Sequence-                : xs-            ) =-            pss hash1 xs-    fromASN1-        ( Start Sequence-                : OID [1, 2, 840, 113549, 1, 1, 10]-                : Start Sequence-                : Start (Container Context 0)-                : Start Sequence-                : OID hash1-                : Null-                : End Sequence-                : End (Container Context 0)-                : Start (Container Context 1)-                : Start Sequence-                : OID [1, 2, 840, 113549, 1, 1, 8]-                : Start Sequence-                : OID _hash2-                : Null-                : End Sequence-                : End Sequence-                : End (Container Context 1)-                : Start (Container Context 2)-                : IntVal _iv-                : End (Container Context 2)-                : End Sequence-                : End Sequence-                : xs-            ) =-            pss hash1 xs-    -- RSASSA-PSS with all parameters defaulted: SHA-1, MGF1 with SHA-1, salt 20-    fromASN1-        ( Start Sequence-                : OID [1, 2, 840, 113549, 1, 1, 10]-                : Start Sequence-                : End Sequence-                : End Sequence-                : xs-            ) =-            Right (SignatureALG HashSHA1 PubKeyALG_RSAPSS, xs)+    fromASN1 (Start Sequence : OID oid : Start Sequence : xs)+        | oid == oidRSAPSS = do+            (p, ys) <- parsePSSParams xs+            case ys of+                End Sequence : zs -> Right (rsaPSSSignatureALG p, zs)+                _ -> Left "fromASN1: X509.SignatureALG: invalid PSS parameters"     fromASN1 _ =         Left "fromASN1: X509.SignatureALG: unknown format"     toASN1 (SignatureALG_Unknown oid) = \xs -> Start Sequence : OID oid : Null : End Sequence : xs-    toASN1 (SignatureALG HashSHA1 PubKeyALG_RSAPSS) = \xs ->-        Start Sequence-            : OID [1, 2, 840, 113549, 1, 1, 10]-            : Start Sequence-            : End Sequence-            : End Sequence-            : xs-    toASN1 (SignatureALG hashAlg PubKeyALG_RSAPSS) = \xs ->-        Start Sequence-            : OID [1, 2, 840, 113549, 1, 1, 10]-            : Start Sequence-            : Start (Container Context 0)-            : Start Sequence-            : OID (pssHashOID hashAlg)-            : End Sequence-            : End (Container Context 0)-            : Start (Container Context 1)-            : Start Sequence-            : OID [1, 2, 840, 113549, 1, 1, 8]-            : Start Sequence-            : OID (pssHashOID hashAlg)-            : End Sequence-            : End Sequence-            : End (Container Context 1)-            : Start (Container Context 2)-            : IntVal (saltLen hashAlg)-            : End (Container Context 2)-            : End Sequence-            : End Sequence-            : xs+    toASN1 (SignatureALG h PubKeyALG_RSAPSS) = encodePSSParams (defaultPSSParams h)+    toASN1 (SignatureALG_RSAPSS p) = encodePSSParams p     toASN1 signatureAlg@(SignatureALG_IntrinsicHash _) = \xs -> Start Sequence : OID (sigOID signatureAlg) : End Sequence : xs     -- ECDSA: "the encoding MUST omit the parameters field"     -- (RFC 5758 3.2, RFC 3279 2.2.3)
Data/X509/DistinguishedName.hs view
@@ -1,4 +1,6 @@ {-# LANGUAGE CPP #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}  -- | -- Module      : Data.X509.DistinguishedName@@ -9,7 +11,10 @@ -- -- X.509 Distinguished names types and functions module Data.X509.DistinguishedName (-    DistinguishedName (..),+    DistinguishedName (DistinguishedName, getDistinguishedElements),+    RelativeDistinguishedName,+    getRDNs,+    fromRDNs,     DistinguishedNameInner (..),     ASN1CharacterString (..),     -- Distinguished Name Elements@@ -23,12 +28,37 @@ #endif import Data.ASN1.Types import Data.Char (toLower)+import Data.List (sort) import Data.X509.Internal --- | A list of OID and strings.-newtype DistinguishedName = DistinguishedName {getDistinguishedElements :: [(OID, ASN1CharacterString)]}+-- | A sequence of relative distinguished names.  The constructor is+-- hidden; use 'getRDNs' and 'fromRDNs', or the 'DistinguishedName' pattern+-- for names without multi-valued RDNs.+newtype DistinguishedName = RDNSequence [RelativeDistinguishedName]     deriving (Show, Eq, Ord) +-- | A set of attribute types and values, usually with one element.+type RelativeDistinguishedName = [(OID, ASN1CharacterString)]++-- | The relative distinguished names.+getRDNs :: DistinguishedName -> [RelativeDistinguishedName]+getRDNs (RDNSequence rdns) = rdns++-- | A name from relative distinguished names.+fromRDNs :: [RelativeDistinguishedName] -> DistinguishedName+fromRDNs = RDNSequence++-- | All attributes in order, flattening multi-valued RDNs.  Constructing+-- makes one RDN per attribute.+pattern DistinguishedName+    :: [(OID, ASN1CharacterString)] -> DistinguishedName+pattern DistinguishedName{getDistinguishedElements} <-+    (concat . getRDNs -> getDistinguishedElements)+    where+        DistinguishedName els = RDNSequence (map (: []) els)++{-# COMPLETE DistinguishedName #-}+ -- | Elements commonly available in a 'DistinguishedName' structure data DnElement     = -- | CN@@ -41,7 +71,37 @@       DnOrganizationUnit     | -- | Email Address (legacy)       DnEmailAddress-    deriving (Show, Eq)+    | -- | L+      DnLocality+    | -- | ST+      DnStateOrProvince+    | -- | Street address+      DnStreetAddress+    | -- | Postal code+      DnPostalCode+    | -- | Serial number+      DnSerialNumber+    | -- | Title+      DnTitle+    | -- | Name+      DnName+    | -- | Surname+      DnSurname+    | -- | Given name+      DnGivenName+    | -- | Initials+      DnInitials+    | -- | Generation qualifier+      DnGenerationQualifier+    | -- | DN qualifier+      DnQualifier+    | -- | Pseudonym+      DnPseudonym+    | -- | DC+      DnDomainComponent+    | -- | UID+      DnUserId+    deriving (Show, Eq, Enum, Bounded)  instance OIDable DnElement where     getObjectID DnCommonName = [2, 5, 4, 3]@@ -49,17 +109,36 @@     getObjectID DnOrganization = [2, 5, 4, 10]     getObjectID DnOrganizationUnit = [2, 5, 4, 11]     getObjectID DnEmailAddress = [1, 2, 840, 113549, 1, 9, 1]+    getObjectID DnLocality = [2, 5, 4, 7]+    getObjectID DnStateOrProvince = [2, 5, 4, 8]+    getObjectID DnStreetAddress = [2, 5, 4, 9]+    getObjectID DnPostalCode = [2, 5, 4, 17]+    getObjectID DnSerialNumber = [2, 5, 4, 5]+    getObjectID DnTitle = [2, 5, 4, 12]+    getObjectID DnName = [2, 5, 4, 41]+    getObjectID DnSurname = [2, 5, 4, 4]+    getObjectID DnGivenName = [2, 5, 4, 42]+    getObjectID DnInitials = [2, 5, 4, 43]+    getObjectID DnGenerationQualifier = [2, 5, 4, 44]+    getObjectID DnQualifier = [2, 5, 4, 46]+    getObjectID DnPseudonym = [2, 5, 4, 65]+    getObjectID DnDomainComponent = [0, 9, 2342, 19200300, 100, 1, 25]+    getObjectID DnUserId = [0, 9, 2342, 19200300, 100, 1, 1] +instance OIDNameable DnElement where+    fromObjectID oid = lookup oid [(getObjectID e, e) | e <- [minBound .. maxBound]]+ -- | Try to get a specific element in a 'DistinguishedName' structure getDnElement :: DnElement -> DistinguishedName -> Maybe ASN1CharacterString-getDnElement element (DistinguishedName els) = lookup (getObjectID element) els+getDnElement element dn = lookup (getObjectID element) $ getDistinguishedElements dn  -- | A form for comparing names (RFC 5280 7.1): string values are--- converted to UTF8String, lower-cased and whitespace is folded.  Values+-- converted to UTF8String, lower-cased and whitespace is folded, and the+-- attributes of each RDN are sorted.  Values -- that cannot be decoded are kept. canonicalDistinguishedName :: DistinguishedName -> DistinguishedName-canonicalDistinguishedName (DistinguishedName els) =-    DistinguishedName [(oid, canon v) | (oid, v) <- els]+canonicalDistinguishedName (RDNSequence rdns) =+    RDNSequence [sort [(oid, canon v) | (oid, v) <- rdn] | rdn <- rdns]   where     canon v = case safeCharacterToString v of         Just str -> asn1CharacterString UTF8 $ unwords $ words $ map toLower str@@ -72,13 +151,13 @@  #if MIN_VERSION_base(4,9,0) instance Semigroup DistinguishedName where-    DistinguishedName l1 <> DistinguishedName l2 = DistinguishedName (l1++l2)+    RDNSequence l1 <> RDNSequence l2 = RDNSequence (l1++l2) #endif  instance Monoid DistinguishedName where-    mempty = DistinguishedName []+    mempty = RDNSequence [] #if !(MIN_VERSION_base(4,11,0))-    mappend (DistinguishedName l1) (DistinguishedName l2) = DistinguishedName (l1++l2)+    mappend (RDNSequence l1) (RDNSequence l2) = RDNSequence (l1++l2) #endif  instance ASN1Object DistinguishedName where@@ -90,15 +169,15 @@ instance ASN1Object DistinguishedNameInner where     toASN1 (DistinguishedNameInner dn) = \xs -> encodeDNinner dn ++ xs     fromASN1 =-        runParseASN1State (DistinguishedNameInner . DistinguishedName <$> parseDNInner)+        runParseASN1State (DistinguishedNameInner . RDNSequence <$> parseDNInner)  parseDN :: ParseASN1 DistinguishedName-parseDN = DistinguishedName <$> onNextContainer Sequence parseDNInner+parseDN = RDNSequence <$> onNextContainer Sequence parseDNInner -parseDNInner :: ParseASN1 [(OID, ASN1CharacterString)]-parseDNInner = concat `fmap` getMany parseOneDN+parseDNInner :: ParseASN1 [RelativeDistinguishedName]+parseDNInner = getMany parseOneDN -parseOneDN :: ParseASN1 [(OID, ASN1CharacterString)]+parseOneDN :: ParseASN1 RelativeDistinguishedName parseOneDN = onNextContainer Set $ getMany $ do     s <- getNextContainer Sequence     case s of@@ -107,9 +186,10 @@             throwParseError ("expecting [OID,String] got " ++ show s)  encodeDNinner :: DistinguishedName -> [ASN1]-encodeDNinner (DistinguishedName dn) = concatMap dnSet dn+encodeDNinner (RDNSequence rdns) = concatMap rdnSet rdns   where-    dnSet (oid, cs) = asn1Container Set $ asn1Container Sequence [OID oid, ASN1String cs]+    rdnSet rdn = asn1Container Set $ concatMap atv rdn+    atv (oid, cs) = asn1Container Sequence [OID oid, ASN1String cs]  encodeDN :: DistinguishedName -> [ASN1] encodeDN dn = asn1Container Sequence $ encodeDNinner dn
Data/X509/Ext.hs view
@@ -1,5 +1,7 @@ {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE ViewPatterns #-}  -- | -- Module      : Data.X509.Ext@@ -20,13 +22,21 @@     ExtKeyUsagePurpose (..),     ExtSubjectKeyId (..),     ExtSubjectAltName (..),-    ExtAuthorityKeyId (..),+    ExtAuthorityKeyId (ExtAuthorityKeyId),+    defaultExtAuthorityKeyId,+    akiKeyIdentifier,+    akiIssuerSerial,     ExtCrlDistributionPoints (..),     ExtNetscapeComment (..),     ExtNameConstraints (..),     GeneralSubtree (..),     AltName (..),-    DistributionPoint (..),+    DistributionPoint,+    defaultDistributionPoint,+    dpName,+    dpReasons,+    dpCRLIssuer,+    DistributionPointName (..),     ReasonFlag (..),      -- * Accessor turning extension into a specific one@@ -47,7 +57,7 @@ import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Data.List (find)-import Data.Maybe (catMaybes)+import Data.Maybe (isNothing) import Data.Proxy import Data.X509.DistinguishedName import Data.X509.ExtensionRaw@@ -226,13 +236,7 @@     extDecode [OctetString o] = Right $ ExtSubjectKeyId o     extDecode _ = Left "unknown sequence" --- | Different naming scheme use by the extension.------ Not all name types are available, missing:--- otherName--- x400Address--- ediPartyName--- registeredID+-- | GeneralName (RFC 5280 4.2.1.6). data AltName     = AltNameRFC822 String     | AltNameDNS String@@ -241,6 +245,15 @@     | AltNameIP B.ByteString     | AltNameXMPP String     | AltNameDNSSRV String+    | -- | otherName other than XMPP and SRV: the type and the DER encoding+      -- of the value+      AltNameOther OID B.ByteString+    | -- | x400Address: the DER encoding of the ORAddress contents+      AltNameX400 B.ByteString+    | -- | ediPartyName: the DER encoding of the EDIPartyName contents+      AltNameEDIParty B.ByteString+    | -- | registeredID+      AltNameRegisteredID OID     deriving (Show, Eq, Ord)  -- | Provide a way to supply alternate name that can be@@ -254,28 +267,54 @@     extEncode (ExtSubjectAltName names) = encodeGeneralNames names     extDecode l = runParseASN1 (ExtSubjectAltName <$> parseGeneralNames) l --- | Provide a mean to identify the public key corresponding to the private key--- used to signed a certificate.-data ExtAuthorityKeyId = ExtAuthorityKeyId B.ByteString+-- | Authority key identifier (RFC 5280 4.2.1.1).  The constructor is+-- hidden; use 'defaultExtAuthorityKeyId' and record update syntax.+data ExtAuthorityKeyId = ExtAuthorityKeyId_+    { akiKeyIdentifier :: Maybe B.ByteString+    -- ^ keyIdentifier+    , akiIssuerSerial :: Maybe ([AltName], Integer)+    -- ^ authorityCertIssuer and authorityCertSerialNumber+    }     deriving (Show, Eq) +-- | No fields.+defaultExtAuthorityKeyId :: ExtAuthorityKeyId+defaultExtAuthorityKeyId = ExtAuthorityKeyId_ Nothing Nothing++-- | An identifier with a keyIdentifier.  Constructing sets only the+-- keyIdentifier.+pattern ExtAuthorityKeyId :: B.ByteString -> ExtAuthorityKeyId+pattern ExtAuthorityKeyId keyid <- ExtAuthorityKeyId_ (Just keyid) _+    where+        ExtAuthorityKeyId keyid = ExtAuthorityKeyId_ (Just keyid) Nothing+ instance Extension ExtAuthorityKeyId where     extOID _ = [2, 5, 29, 35]     extHasNestedASN1 = const True-    extEncode (ExtAuthorityKeyId keyid) =-        [Start Sequence, Other Context 0 keyid, End Sequence]--    -- authorityCertIssuer and authorityCertSerialNumber are not kept-    extDecode (Start Sequence : Other Context 0 keyid : rest)-        | issuerSerial rest = Right $ ExtAuthorityKeyId keyid-      where-        issuerSerial [End Sequence] = True-        issuerSerial (Start (Container Context 1) : xs) =-            case dropWhile (/= End (Container Context 1)) xs of-                _ : [Other Context 2 _, End Sequence] -> True-                _ -> False-        issuerSerial _ = False-    extDecode _ = Left "unknown sequence"+    extEncode (ExtAuthorityKeyId_ keyid issuerSerial) =+        [Start Sequence]+            ++ maybe [] (\k -> [Other Context 0 k]) keyid+            ++ maybe+                []+                ( \(names, serial) ->+                    asn1Container (Container Context 1) (concatMap encodeAltName names)+                        ++ [Other Context 2 (intContent serial)]+                )+                issuerSerial+            ++ [End Sequence]+    extDecode = runParseASN1 $ onNextContainer Sequence $ do+        keyid <- getNextMaybe $ \x -> case x of+            Other Context 0 k -> Just k+            _ -> Nothing+        names <- onNextContainerMaybe (Container Context 1) (getMany getAddr)+        serial <- getNextMaybe $ \x -> case x of+            Other Context 2 n -> Just n+            _ -> Nothing+        issuerSerial <- case (names, serial) of+            (Nothing, Nothing) -> return Nothing+            (Just ns, Just n) -> either throwParseError (\i -> return $ Just (ns, i)) (implicitInt n)+            _ -> throwParseError "AuthorityKeyIdentifier: issuer and serial must be together"+        return $ ExtAuthorityKeyId_ keyid issuerSerial  -- | Identify how CRL information is obtained data ExtCrlDistributionPoints = ExtCrlDistributionPoints [DistributionPoint]@@ -294,10 +333,26 @@     | Reason_AACompromise     deriving (Show, Eq, Ord, Enum) --- | Distribution point as either some GeneralNames or a DN-data DistributionPoint+-- | Distribution point (RFC 5280 4.2.1.13).  The constructor is hidden;+-- use 'defaultDistributionPoint' and record update syntax.+data DistributionPoint = DistributionPoint_+    { dpName :: Maybe DistributionPointName+    -- ^ distributionPoint+    , dpReasons :: Maybe [ReasonFlag]+    -- ^ reasons+    , dpCRLIssuer :: Maybe [AltName]+    -- ^ cRLIssuer+    }+    deriving (Show, Eq)++-- | No fields.  A distribution point needs a name or a CRL issuer.+defaultDistributionPoint :: DistributionPoint+defaultDistributionPoint = DistributionPoint_ Nothing Nothing Nothing++-- | The name of a distribution point.+data DistributionPointName     = DistributionPointFullName [AltName]-    | DistributionNameRelative DistinguishedName+    | DistributionPointRelativeName RelativeDistinguishedName     deriving (Show, Eq)  instance Extension ExtCrlDistributionPoints where@@ -306,48 +361,62 @@     extEncode (ExtCrlDistributionPoints dps) =         asn1Container Sequence $ concatMap encodeDP dps       where-        encodeDP dp = asn1Container Sequence $ asn1Container (Container Context 0) $ case dp of-            DistributionPointFullName names ->-                asn1Container (Container Context 0) $ concatMap encodeAltName names-            DistributionNameRelative (DistinguishedName els) ->-                asn1Container (Container Context 1) $-                    concat [asn1Container Sequence [OID o, ASN1String v] | (o, v) <- els]+        encodeDP (DistributionPoint_ name rs issuer) =+            asn1Container Sequence $+                maybe [] (asn1Container (Container Context 0) . encodeName) name+                    ++ maybe [] (\r -> [Other Context 1 (bitsContent (flagsToBits r))]) rs+                    ++ maybe+                        []+                        (asn1Container (Container Context 2) . concatMap encodeAltName)+                        issuer+        encodeName (DistributionPointFullName names) =+            asn1Container (Container Context 0) $ concatMap encodeAltName names+        encodeName (DistributionPointRelativeName rdn) =+            asn1Container (Container Context 1) $+                concat [asn1Container Sequence [OID o, ASN1String v] | (o, v) <- rdn]+        bitsContent bits =+            B.cons+                (fromIntegral $ (8 - bitArrayLength bits `mod` 8) `mod` 8)+                (bitArrayGetData bits)     extDecode = runParseASN1 (ExtCrlDistributionPoints <$> parseDPs)       where         parseDPs = onNextContainer Sequence $ do             dps <- getMany parseDP             when (null dps) $ throwParseError "CRLDistributionPoints: empty"-            return $ catMaybes dps-        -- only the distribution point name is kept: reasons and cRLIssuer-        -- are dropped, and so are points without a name+            return dps         parseDP = onNextContainer Sequence $ do             name <- onNextContainerMaybe (Container Context 0) parseName-            _ <- getNextMaybe reasons-            _ <- onNextContainerMaybe (Container Context 2) (getMany getAddrMaybe)-            return name+            rs <- getNextMaybe reasons+            rs' <- maybe (return Nothing) (fmap Just . either throwParseError return) rs+            issuer <- onNextContainerMaybe (Container Context 2) (getMany getAddr)+            when (isNothing name && isNothing issuer) $+                throwParseError "DistributionPoint: no name or CRL issuer"+            return $ DistributionPoint_ name rs' issuer         parseName = do-            full <--                onNextContainerMaybe (Container Context 0) (catMaybes <$> getMany getAddrMaybe)+            full <- onNextContainerMaybe (Container Context 0) (getMany getAddr)             case full of                 Just names -> return $ DistributionPointFullName names                 Nothing ->                     maybe (throwParseError "DistributionPoint: unknown name") return                         =<< onNextContainerMaybe                             (Container Context 1)-                            (DistributionNameRelative . DistinguishedName <$> getMany parseATV)+                            (DistributionPointRelativeName <$> getMany parseATV)         parseATV = onNextContainer Sequence $ do             o <- getNext             v <- getNext             case (o, v) of                 (OID oid, ASN1String str) -> return (oid, str)                 _ -> throwParseError "DistributionPoint: invalid attribute"-        reasons (Other Context 1 _) = Just ()+        reasons (Other Context 1 bs) = Just $ case B.uncons bs of+            Just (unused, d)+                | unused < 8 && not (B.null d && unused /= 0) ->+                    Right $ bitsToFlags Reason_AACompromise (toBitArray d (fromIntegral unused))+            _ -> Left "DistributionPoint: invalid reasons"         reasons _ = Nothing --- | GeneralName types that 'AltName' cannot represent are skipped. parseGeneralNames :: ParseASN1 [AltName] parseGeneralNames = onNextContainer Sequence $ do-    names <- catMaybes <$> getMany getAddrMaybe+    names <- getMany getAddr     forM_ names $ \name -> case name of         AltNameIP ip             | B.length ip /= 4 && B.length ip /= 16 ->@@ -355,23 +424,16 @@         _ -> return ()     return names --- | Fails on GeneralName types that 'AltName' cannot represent. getAddr :: ParseASN1 AltName-getAddr =-    getAddrMaybe-        >>= maybe (throwParseError "GeneralNames: unsupported name type") return---- | 'Nothing' for a well-formed GeneralName of an unsupported type.-getAddrMaybe :: ParseASN1 (Maybe AltName)-getAddrMaybe = do+getAddr = do     m <- onNextContainerMaybe (Container Context 0) getComposedAddr     case m of         Just r -> return r         Nothing -> do             d <- onNextContainerMaybe (Container Context 4) getObject             case d of-                Just dn -> return $ Just $ AltNameDN dn-                Nothing -> getUnsupportedOrSimpleAddr+                Just dn -> return $ AltNameDN dn+                Nothing -> getConstructedOrSimpleAddr   where     getComposedAddr = do         n <- getNext@@ -383,7 +445,7 @@                     Just [ASN1String cs] ->                         case safeCharacterToString cs of                             Nothing -> throwParseError ("GeneralNames: invalid string for XMPP Addr")-                            Just s -> return $ Just $ AltNameXMPP s+                            Just s -> return $ AltNameXMPP s                     _ ->                         throwParseError ("GeneralNames: expecting string for XMPP Addr got: " ++ show c)             OID [1, 3, 6, 1, 5, 5, 7, 8, 7] -> do@@ -393,35 +455,79 @@                     Just [ASN1String cs] ->                         case safeCharacterToString cs of                             Nothing -> throwParseError ("GeneralNames: invalid string for DNSSrv Addr")-                            Just s -> return $ Just $ AltNameDNSSRV s+                            Just s -> return $ AltNameDNSSRV s                     _ ->                         throwParseError                             ("GeneralNames: expecting string for DNSSRV Addr got: " ++ show c)-            OID _ -> getMany getNext >> return Nothing -- unknown otherName+            OID oid -> do+                c <- getNextContainerMaybe (Container Context 0)+                case c of+                    Just v@(_ : _) -> return $ AltNameOther oid (encodeASN1' DER v)+                    _ -> throwParseError "GeneralNames: invalid otherName"             _ -> throwParseError ("GeneralNames: expecting OID but got " ++ show n)      getSimpleAddr = do         n <- getNext         case n of-            (Other Context 1 b) -> return $ Just $ AltNameRFC822 $ BC.unpack b-            (Other Context 2 b) -> return $ Just $ AltNameDNS $ BC.unpack b+            (Other Context 1 b) -> return $ AltNameRFC822 $ BC.unpack b+            (Other Context 2 b) -> return $ AltNameDNS $ BC.unpack b             -- directoryName as written by older versions of this library             (Other Context 4 b) -> case safeDecode (decodeASN1' DER b) of                 Left e1 -> throwParseError e1                 Right as -> case runParseASN1 getObject as of-                    Right dn -> return $ Just $ AltNameDN dn+                    Right dn -> return $ AltNameDN dn                     Left e2 -> throwParseError e2-            (Other Context 6 b) -> return $ Just $ AltNameURI $ BC.unpack b-            (Other Context 7 b) -> return $ Just $ AltNameIP b-            (Other Context 8 _) -> return Nothing -- registeredID+            (Other Context 6 b) -> return $ AltNameURI $ BC.unpack b+            (Other Context 7 b) -> return $ AltNameIP b+            (Other Context 8 b) -> case decodeOID b of+                Just oid -> return $ AltNameRegisteredID oid+                Nothing -> throwParseError "GeneralNames: invalid registeredID"             _ ->                 throwParseError ("GeneralNames: not coping with unknown stream " ++ show n)-    -- x400Address and ediPartyName are skipped-    getUnsupportedOrSimpleAddr = do+    getConstructedOrSimpleAddr = do         x400 <- getNextContainerMaybe (Container Context 3)-        edi <- maybe (getNextContainerMaybe (Container Context 5)) (return . Just) x400-        maybe getSimpleAddr (const $ return Nothing) edi+        case x400 of+            Just v -> return $ AltNameX400 (encodeASN1' DER v)+            Nothing -> do+                edi <- getNextContainerMaybe (Container Context 5)+                case edi of+                    Just v -> return $ AltNameEDIParty (encodeASN1' DER v)+                    Nothing -> getSimpleAddr +-- | The content octets of an OBJECT IDENTIFIER.+decodeOID :: B.ByteString -> Maybe OID+decodeOID bs+    | B.null bs || B.last bs >= 0x80 = Nothing+    | otherwise = case subids (B.unpack bs) of+        (x : xs)+            | x < 40 -> Just (0 : x : xs)+            | x < 80 -> Just (1 : (x - 40) : xs)+            | otherwise -> Just (2 : (x - 80) : xs)+        [] -> Nothing+  where+    subids [] = []+    subids ws =+        let (more, rest) = span (>= 0x80) ws+         in case rest of+                (w : rest') ->+                    foldl (\a v -> a * 128 + fromIntegral (v .&. 0x7f)) 0 (more ++ [w])+                        : subids rest'+                [] -> []++encodeOID :: OID -> B.ByteString+encodeOID (a : b : xs) = B.pack $ concatMap base128 (a * 40 + b : xs)+  where+    base128 n =+        let go 0 acc = acc+            go m acc = go (m `shiftR` 7) ((fromIntegral (m .&. 0x7f) .|. 0x80) : acc)+            lastByte = fromIntegral (n .&. 0x7f)+         in go (n `shiftR` 7) [lastByte]+encodeOID _ = B.empty++-- | Decode the contents of a constructed field written as DER.+derContents :: B.ByteString -> [ASN1]+derContents = either (const []) id . decodeASN1' DER+ encodeGeneralNames :: [AltName] -> [ASN1] encodeGeneralNames names =     [Start Sequence]@@ -451,6 +557,15 @@     , End (Container Context 0)     , End (Container Context 0)     ]+encodeAltName (AltNameOther oid v) =+    [Start (Container Context 0), OID oid, Start (Container Context 0)]+        ++ derContents v+        ++ [End (Container Context 0), End (Container Context 0)]+encodeAltName (AltNameX400 v) =+    [Start (Container Context 3)] ++ derContents v ++ [End (Container Context 3)]+encodeAltName (AltNameEDIParty v) =+    [Start (Container Context 5)] ++ derContents v ++ [End (Container Context 5)]+encodeAltName (AltNameRegisteredID oid) = [Other Context 8 $ encodeOID oid]  -- | Bits beyond the last known flag (the first argument) or beyond the -- actual data (a bogus length) are ignored.@@ -538,13 +653,6 @@         ++ (if minimum' /= 0 then [Other Context 0 (intContent minimum')] else [])         ++ maybe [] (\m -> [Other Context 1 (intContent m)]) maximum'         ++ [End Sequence]-  where-    -- the content octets of an IMPLICIT INTEGER (two's complement)-    intContent = B.pack . go-      where-        go i-            | i >= -128 && i < 128 = [fromIntegral i]-            | otherwise = go (i `shiftR` 8) ++ [fromIntegral (i .&. 0xff)]  -------------------------------------------------------------------------------- -- Decoding@@ -604,10 +712,18 @@ decodeGeneralSubtree _ =     Left "GeneralSubtree: invalid ASN1" +-- | The content octets of an IMPLICIT INTEGER (two's complement).+intContent :: Integer -> B.ByteString+intContent = B.pack . go+  where+    go i+        | i >= -128 && i < 128 = [fromIntegral i]+        | otherwise = go (i `shiftR` 8) ++ [fromIntegral (i .&. 0xff)]+ -- | Decode the content octets of an IMPLICIT INTEGER. implicitInt :: B.ByteString -> Either String Integer implicitInt bs-    | B.null bs = Left "GeneralSubtree: empty integer"+    | B.null bs = Left "empty integer"     | otherwise = Right $ B.foldl' (\a w -> a * 256 + fromIntegral w) sign bs   where     sign = if testBit (B.head bs) 7 then -1 else 0
Data/X509/PrivateKey.hs view
@@ -1,5 +1,9 @@+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE StandaloneDeriving #-}+ -- |--- Module      : Data.X509.PublicKey+-- Module      : Data.X509.PrivateKey -- License     : BSD-style -- Maintainer  : Vincent Hanquez <vincent@snarc.org> -- Stability   : experimental@@ -10,12 +14,22 @@     PrivKey (..),     PrivKeyEC (..),     PrivKeyMLDSA,-    MLDSAKeyForm (..),+    MLKeyForm (..),+    MLDSAKeyForm,+    pattern MLDSAKeySeed,+    pattern MLDSAKeyExpanded,+    pattern MLDSAKeyBoth,     privkeyMLDSAFromSeed,     privkeyMLDSAFromKey,     privkeyMLDSA_key,     privkeyMLDSA_seed,     privkeyMLDSA_form,+    PrivKeyMLKEM,+    privkeyMLKEMFromSeed,+    privkeyMLKEMFromKey,+    privkeyMLKEM_key,+    privkeyMLKEM_seed,+    privkeyMLKEM_form,     privkeyToAlg, ) where @@ -47,6 +61,7 @@ import qualified Crypto.PubKey.Ed25519 as Ed25519 import qualified Crypto.PubKey.Ed448 as Ed448 import qualified Crypto.PubKey.MLDSA as MLDSA+import qualified Crypto.PubKey.MLKEM as MLKEM import qualified Crypto.PubKey.RSA as RSA  -- | Elliptic Curve Private Key@@ -109,17 +124,40 @@             . priv             . showChar '}' --- | Which of the three forms of RFC 9881 Section 6 a private key was read--- as, and is written back out as.-data MLDSAKeyForm+-- | Which of the three forms of an ML-DSA (RFC 9881 Section 6) or ML-KEM+-- (RFC 9935 Section 6) private key a key was read as, and is written back+-- out as.+data MLKeyForm     = -- | The seed alone, @seed@, which Section 6 recommends.-      MLDSAKeySeed+      MLKeySeed     | -- | The expanded key alone, @expandedKey@.-      MLDSAKeyExpanded+      MLKeyExpanded     | -- | Both together, @both@.-      MLDSAKeyBoth+      MLKeyBoth     deriving (Show, Eq) +-- | The former name of 'MLKeyForm'.+type MLDSAKeyForm = MLKeyForm++{-# DEPRECATED MLDSAKeyForm "Use MLKeyForm" #-}++-- | The former name of 'MLKeySeed'.+pattern MLDSAKeySeed :: MLKeyForm+pattern MLDSAKeySeed = MLKeySeed++-- | The former name of 'MLKeyExpanded'.+pattern MLDSAKeyExpanded :: MLKeyForm+pattern MLDSAKeyExpanded = MLKeyExpanded++-- | The former name of 'MLKeyBoth'.+pattern MLDSAKeyBoth :: MLKeyForm+pattern MLDSAKeyBoth = MLKeyBoth++{-# COMPLETE MLDSAKeySeed, MLDSAKeyExpanded, MLDSAKeyBoth #-}+{-# DEPRECATED MLDSAKeySeed "Use MLKeySeed" #-}+{-# DEPRECATED MLDSAKeyExpanded "Use MLKeyExpanded" #-}+{-# DEPRECATED MLDSAKeyBoth "Use MLKeyBoth" #-}+ -- | An ML-DSA private key. -- -- RFC 9881 Section 6 writes one as the seed it was derived from, as the@@ -177,18 +215,18 @@ -- | Build a key from its seed, to be written back out in the given form. -- -- The expanded key is derived here, so it cannot fail to be the one the--- seed belongs to.  Passing 'MLDSAKeyExpanded' throws the seed away, which+-- seed belongs to.  Passing 'MLKeyExpanded' throws the seed away, which -- is the way to turn a seed into a key that will be written without one. privkeyMLDSAFromSeed     :: (MLDSA.MLDSA p, ByteArrayAccess ba)-    => proxy p -> MLDSAKeyForm -> ba -> CryptoFailable (PrivKeyMLDSA p)+    => proxy p -> MLKeyForm -> ba -> CryptoFailable (PrivKeyMLDSA p) privkeyMLDSAFromSeed p form bs = case MLDSA.keyPairFromSeed p bs of     CryptoFailed e -> CryptoFailed e     CryptoPassed (_, sk) ->         CryptoPassed $ case form of-            MLDSAKeySeed -> PrivKeyMLDSA_Seed seed sk-            MLDSAKeyExpanded -> PrivKeyMLDSA_Expanded sk-            MLDSAKeyBoth -> PrivKeyMLDSA_Both seed sk+            MLKeySeed -> PrivKeyMLDSA_Seed seed sk+            MLKeyExpanded -> PrivKeyMLDSA_Expanded sk+            MLKeyBoth -> PrivKeyMLDSA_Both seed sk   where     seed = convert bs :: ScrubbedBytes @@ -210,15 +248,81 @@ privkeyMLDSA_seed (PrivKeyMLDSA_Both s _) = Just s  -- | The form the key will be written out in.-privkeyMLDSA_form :: PrivKeyMLDSA p -> MLDSAKeyForm-privkeyMLDSA_form (PrivKeyMLDSA_Seed _ _) = MLDSAKeySeed-privkeyMLDSA_form (PrivKeyMLDSA_Expanded _) = MLDSAKeyExpanded-privkeyMLDSA_form (PrivKeyMLDSA_Both _ _) = MLDSAKeyBoth+privkeyMLDSA_form :: PrivKeyMLDSA p -> MLKeyForm+privkeyMLDSA_form (PrivKeyMLDSA_Seed _ _) = MLKeySeed+privkeyMLDSA_form (PrivKeyMLDSA_Expanded _) = MLKeyExpanded+privkeyMLDSA_form (PrivKeyMLDSA_Both _ _) = MLKeyBoth +-- | An ML-KEM private key, kept in the form it was read as, like+-- 'PrivKeyMLDSA'.  The constructors are not exported.+data PrivKeyMLKEM p+    = PrivKeyMLKEM_Seed ScrubbedBytes (MLKEM.DecapsulationKey p)+    | PrivKeyMLKEM_Expanded (MLKEM.DecapsulationKey p)+    | PrivKeyMLKEM_Both ScrubbedBytes (MLKEM.DecapsulationKey p)++deriving instance MLKEM.MLKEM p => Eq (PrivKeyMLKEM p)++showsPrivKeyMLKEM+    :: (ScrubbedBytes -> String)+    -> (MLKEM.DecapsulationKey p -> String)+    -> PrivKeyMLKEM p+    -> String+showsPrivKeyMLKEM seed key k = case k of+    PrivKeyMLKEM_Seed s sk -> con "PrivKeyMLKEM_Seed" [seed s, key sk]+    PrivKeyMLKEM_Expanded sk -> con "PrivKeyMLKEM_Expanded" [key sk]+    PrivKeyMLKEM_Both s sk -> con "PrivKeyMLKEM_Both" [seed s, key sk]+  where+    con name as = unwords (name : map (\a -> "(" ++ a ++ ")") as)++-- | The form is shown; neither the seed nor the key is.+instance MLKEM.MLKEM p => Show (PrivKeyMLKEM p) where+    show = showsPrivKeyMLKEM (const "<secret>") show++instance MLKEM.MLKEM p => DebugShow (PrivKeyMLKEM p) where+    debugShow = showsPrivKeyMLKEM (debugShowBytes "seed") debugShow++-- | Build a key from its seed, to be written back out in the given form.+privkeyMLKEMFromSeed+    :: (MLKEM.MLKEM p, ByteArrayAccess ba)+    => proxy p -> MLKeyForm -> ba -> CryptoFailable (PrivKeyMLKEM p)+privkeyMLKEMFromSeed p form bs = case MLKEM.keyPairFromSeed p bs of+    CryptoFailed e -> CryptoFailed e+    CryptoPassed (_, sk) ->+        CryptoPassed $ case form of+            MLKeySeed -> PrivKeyMLKEM_Seed seed sk+            MLKeyExpanded -> PrivKeyMLKEM_Expanded sk+            MLKeyBoth -> PrivKeyMLKEM_Both seed sk+  where+    seed = convert bs :: ScrubbedBytes++-- | Build a key from the expanded key alone.+privkeyMLKEMFromKey :: MLKEM.DecapsulationKey p -> PrivKeyMLKEM p+privkeyMLKEMFromKey = PrivKeyMLKEM_Expanded++-- | The expanded key, whatever form the key is in.+privkeyMLKEM_key :: PrivKeyMLKEM p -> MLKEM.DecapsulationKey p+privkeyMLKEM_key (PrivKeyMLKEM_Seed _ sk) = sk+privkeyMLKEM_key (PrivKeyMLKEM_Expanded sk) = sk+privkeyMLKEM_key (PrivKeyMLKEM_Both _ sk) = sk++-- | The seed, for a key that has one.+privkeyMLKEM_seed :: PrivKeyMLKEM p -> Maybe ScrubbedBytes+privkeyMLKEM_seed (PrivKeyMLKEM_Seed s _) = Just s+privkeyMLKEM_seed (PrivKeyMLKEM_Expanded _) = Nothing+privkeyMLKEM_seed (PrivKeyMLKEM_Both s _) = Just s++-- | The form the key will be written out in.+privkeyMLKEM_form :: PrivKeyMLKEM p -> MLKeyForm+privkeyMLKEM_form (PrivKeyMLKEM_Seed _ _) = MLKeySeed+privkeyMLKEM_form (PrivKeyMLKEM_Expanded _) = MLKeyExpanded+privkeyMLKEM_form (PrivKeyMLKEM_Both _ _) = MLKeyBoth+ -- | Private key types known and used in X.509 data PrivKey     = -- | RSA private key       PrivKeyRSA RSA.PrivateKey+    | -- | RSASSA-PSS private key, restricted to the parameters if any+      PrivKeyRSAPSS RSA.PrivateKey (Maybe PSSParams)     | -- | DSA private key       PrivKeyDSA DSA.PrivateKey     | -- | EC private key@@ -237,6 +341,12 @@       PrivKeyMLDSA65 (PrivKeyMLDSA MLDSA.MLDSA65)     | -- | ML-DSA-87 private key       PrivKeyMLDSA87 (PrivKeyMLDSA MLDSA.MLDSA87)+    | -- | ML-KEM-512 private key+      PrivKeyMLKEM512 (PrivKeyMLKEM MLKEM.MLKEM512)+    | -- | ML-KEM-768 private key+      PrivKeyMLKEM768 (PrivKeyMLKEM MLKEM.MLKEM768)+    | -- | ML-KEM-1024 private key+      PrivKeyMLKEM1024 (PrivKeyMLKEM MLKEM.MLKEM1024)     deriving (Show, Eq)  -- | Rendering a private key with the key material in it, for the times when@@ -245,6 +355,7 @@ instance DebugShow PrivKey where     debugShow k = case k of         PrivKeyRSA p -> con "PrivKeyRSA" $ debugShow p+        PrivKeyRSAPSS p mp -> con "PrivKeyRSAPSS" (debugShow p ++ ") (" ++ show mp)         PrivKeyDSA p -> con "PrivKeyDSA" $ debugShow p         PrivKeyEC p -> con "PrivKeyEC" $ debugShow p         PrivKeyX25519 p -> con "PrivKeyX25519" $ debugShow p@@ -254,6 +365,9 @@         PrivKeyMLDSA44 p -> con "PrivKeyMLDSA44" $ debugShow p         PrivKeyMLDSA65 p -> con "PrivKeyMLDSA65" $ debugShow p         PrivKeyMLDSA87 p -> con "PrivKeyMLDSA87" $ debugShow p+        PrivKeyMLKEM512 p -> con "PrivKeyMLKEM512" $ debugShow p+        PrivKeyMLKEM768 p -> con "PrivKeyMLKEM768" $ debugShow p+        PrivKeyMLKEM1024 p -> con "PrivKeyMLKEM1024" $ debugShow p       where         con name body = name ++ " (" ++ body ++ ")" @@ -264,6 +378,7 @@ privkeyFromASN1 :: [ASN1] -> Either String (PrivKey, [ASN1]) privkeyFromASN1 asn1 =     (mapFst PrivKeyRSA <$> rsaFromASN1 asn1)+        <!> rsaPSSFromASN1 asn1         <!> (mapFst PrivKeyDSA <$> dsaFromASN1 asn1)         <!> (mapFst PrivKeyEC <$> ecdsaFromASN1 asn1)         <!> newcurveFromASN1 asn1@@ -304,6 +419,21 @@         failure = ("rsaFromASN1: " ++) rsaFromASN1 _ = Left "rsaFromASN1: unexpected format" +-- | PKCS #8 RSASSA-PSS key (RFC 4055).+rsaPSSFromASN1 :: [ASN1] -> Either String (PrivKey, [ASN1])+rsaPSSFromASN1 (Start Sequence : IntVal 0 : Start Sequence : OID oid : xs)+    | oid == getObjectID PubKeyALG_RSAPSS = do+        (mp, ys) <- pssKeyParamsFromASN1 xs+        case ys of+            OctetString bytes : End Sequence : as -> do+                asn1 <- mapLeft ("rsaPSSFromASN1: " ++) (safeDecode $ decodeASN1' BER bytes)+                case rsaFromASN1 asn1 of+                    Right (k, []) -> Right (PrivKeyRSAPSS k mp, as)+                    Right _ -> Left "rsaPSSFromASN1: trailing data"+                    Left err -> Left err+            _ -> Left "rsaPSSFromASN1: unexpected format"+rsaPSSFromASN1 _ = Left "rsaPSSFromASN1: unexpected format"+ dsaFromASN1 :: [ASN1] -> Either String (DSA.PrivateKey, [ASN1]) dsaFromASN1     ( Start Sequence : IntVal 0 : IntVal p : IntVal q : IntVal g@@ -455,6 +585,21 @@                 ( "ML-DSA-87"                 , mldsaFromASN1 (Proxy :: Proxy MLDSA.MLDSA87) PrivKeyMLDSA87 "ML-DSA-87"                 )+        getMLDSA [2, 16, 840, 1, 101, 3, 4, 4, 1] =+            Just+                ( "ML-KEM-512"+                , mlkemFromASN1 (Proxy :: Proxy MLKEM.MLKEM512) PrivKeyMLKEM512 "ML-KEM-512"+                )+        getMLDSA [2, 16, 840, 1, 101, 3, 4, 4, 2] =+            Just+                ( "ML-KEM-768"+                , mlkemFromASN1 (Proxy :: Proxy MLKEM.MLKEM768) PrivKeyMLKEM768 "ML-KEM-768"+                )+        getMLDSA [2, 16, 840, 1, 101, 3, 4, 4, 3] =+            Just+                ( "ML-KEM-1024"+                , mlkemFromASN1 (Proxy :: Proxy MLKEM.MLKEM1024) PrivKeyMLKEM1024 "ML-KEM-1024"+                )         getMLDSA _ = Nothing         isValidVersion version = version >= 0 && version <= 1 newcurveFromASN1 _ =@@ -472,10 +617,10 @@     -> [ASN1]     -> Either String PrivKey mldsaFromASN1 p con name inner = case inner of-    [Other Context 0 seed] -> con <$> fromSeed MLDSAKeySeed seed+    [Other Context 0 seed] -> con <$> fromSeed MLKeySeed seed     [OctetString expanded] -> con . privkeyMLDSAFromKey <$> fromExpanded expanded     [Start Sequence, OctetString seed, OctetString expanded, End Sequence] -> do-        k <- fromSeed MLDSAKeyBoth seed+        k <- fromSeed MLKeyBoth seed         sk <- fromExpanded expanded         if privkeyMLDSA_key k == sk             then Right (con k)@@ -490,6 +635,34 @@         CryptoPassed sk -> Right sk         CryptoFailed e -> err ("invalid expandedKey: " ++ show e) +-- | The private key of RFC 9935 Section 6, in the same three forms as+-- 'mldsaFromASN1'.+mlkemFromASN1+    :: MLKEM.MLKEM p+    => proxy p+    -> (PrivKeyMLKEM p -> PrivKey)+    -> String+    -> [ASN1]+    -> Either String PrivKey+mlkemFromASN1 p con name inner = case inner of+    [Other Context 0 seed] -> con <$> fromSeed MLKeySeed seed+    [OctetString expanded] -> con . privkeyMLKEMFromKey <$> fromExpanded expanded+    [Start Sequence, OctetString seed, OctetString expanded, End Sequence] -> do+        k <- fromSeed MLKeyBoth seed+        sk <- fromExpanded expanded+        if privkeyMLKEM_key k == sk+            then Right (con k)+            else err "seed and expandedKey do not match"+    _ -> err "unexpected inner format"+  where+    err s = Left (name ++ ".DecapsulationKey.fromASN1: " ++ s)+    fromSeed form seed = case privkeyMLKEMFromSeed p form seed of+        CryptoPassed k -> Right k+        CryptoFailed e -> err ("invalid seed: " ++ show e)+    fromExpanded expanded = case MLKEM.decapsulationKey expanded of+        CryptoPassed sk -> Right sk+        CryptoFailed e -> err ("invalid expandedKey: " ++ show e)+ containerWithTag :: ASN1Tag -> [ASN1] -> ([ASN1], [ASN1]) containerWithTag etag (Start (Container _ atag) : xs)     | etag == atag = getConstructedEnd 0 xs@@ -502,6 +675,11 @@  privkeyToASN1 :: PrivKey -> ASN1S privkeyToASN1 (PrivKeyRSA rsa) = rsaToASN1 rsa+privkeyToASN1 (PrivKeyRSAPSS rsa mp) =+    (++) $+        Start Sequence+            : IntVal 0+            : pssKeyAlgToASN1 mp [OctetString (encodeASN1' DER (rsaToASN1 rsa [])), End Sequence] privkeyToASN1 (PrivKeyDSA dsa) = dsaToASN1 dsa privkeyToASN1 (PrivKeyEC ecdsa) = ecdsaToASN1 ecdsa privkeyToASN1 (PrivKeyX25519 k) = newcurveToASN1 [1, 3, 101, 110] k@@ -511,6 +689,9 @@ privkeyToASN1 (PrivKeyMLDSA44 k) = mldsaToASN1 (getObjectID PubKeyALG_MLDSA44) k privkeyToASN1 (PrivKeyMLDSA65 k) = mldsaToASN1 (getObjectID PubKeyALG_MLDSA65) k privkeyToASN1 (PrivKeyMLDSA87 k) = mldsaToASN1 (getObjectID PubKeyALG_MLDSA87) k+privkeyToASN1 (PrivKeyMLKEM512 k) = mlkemToASN1 (getObjectID PubKeyALG_MLKEM512) k+privkeyToASN1 (PrivKeyMLKEM768 k) = mlkemToASN1 (getObjectID PubKeyALG_MLKEM768) k+privkeyToASN1 (PrivKeyMLKEM1024 k) = mlkemToASN1 (getObjectID PubKeyALG_MLKEM1024) k  rsaToASN1 :: RSA.PrivateKey -> ASN1S rsaToASN1 key =@@ -633,6 +814,29 @@             , End Sequence             ] +-- | The inverse of 'mlkemFromASN1'.+mlkemToASN1 :: MLKEM.MLKEM p => OID -> PrivKeyMLKEM p -> ASN1S+mlkemToASN1 oid k =+    (++)+        [ Start Sequence+        , IntVal 0+        , Start Sequence+        , OID oid+        , End Sequence+        , OctetString (encodeASN1' DER inner)+        , End Sequence+        ]+  where+    inner = case k of+        PrivKeyMLKEM_Seed s _ -> [Other Context 0 (convert s)]+        PrivKeyMLKEM_Expanded sk -> [OctetString (convert sk)]+        PrivKeyMLKEM_Both s sk ->+            [ Start Sequence+            , OctetString (convert s)+            , OctetString (convert sk)+            , End Sequence+            ]+ mapLeft :: (a0 -> a1) -> Either a0 b -> Either a1 b mapLeft f (Left x) = Left (f x) mapLeft _ (Right x) = Right x@@ -640,6 +844,7 @@ -- | Convert a Private key to the Public Key Algorithm type privkeyToAlg :: PrivKey -> PubKeyALG privkeyToAlg (PrivKeyRSA _) = PubKeyALG_RSA+privkeyToAlg (PrivKeyRSAPSS _ _) = PubKeyALG_RSAPSS privkeyToAlg (PrivKeyDSA _) = PubKeyALG_DSA privkeyToAlg (PrivKeyEC _) = PubKeyALG_EC privkeyToAlg (PrivKeyX25519 _) = PubKeyALG_X25519@@ -649,3 +854,6 @@ privkeyToAlg (PrivKeyMLDSA44 _) = PubKeyALG_MLDSA44 privkeyToAlg (PrivKeyMLDSA65 _) = PubKeyALG_MLDSA65 privkeyToAlg (PrivKeyMLDSA87 _) = PubKeyALG_MLDSA87+privkeyToAlg (PrivKeyMLKEM512 _) = PubKeyALG_MLKEM512+privkeyToAlg (PrivKeyMLKEM768 _) = PubKeyALG_MLKEM768+privkeyToAlg (PrivKeyMLKEM1024 _) = PubKeyALG_MLKEM1024
Data/X509/PublicKey.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE TypeApplications #-}+ -- | -- Module      : Data.X509.PublicKey -- License     : BSD-style@@ -9,6 +11,14 @@ module Data.X509.PublicKey (     PubKey (..),     PubKeyEC (..),+    PubKeyDH,+    dhPublicKey,+    pubkeyDH_p,+    pubkeyDH_g,+    pubkeyDH_q,+    pubkeyDH_j,+    pubkeyDH_validation,+    pubkeyDH_y,     SerializedPoint (..),     pubkeyToAlg, ) where@@ -36,6 +46,7 @@ import qualified Crypto.PubKey.Ed25519 as Ed25519 import qualified Crypto.PubKey.Ed448 as Ed448 import qualified Crypto.PubKey.MLDSA as MLDSA+import qualified Crypto.PubKey.MLKEM as MLKEM import qualified Crypto.PubKey.RSA.Types as RSA import Data.Word @@ -65,14 +76,39 @@         }     deriving (Show, Eq) +-- | X9.42 Diffie-Hellman public key (RFC 3279 2.3.3).  The constructor is+-- hidden; use 'dhPublicKey' and record update syntax.+data PubKeyDH = PubKeyDH_+    { pubkeyDH_p :: Integer+    -- ^ the prime+    , pubkeyDH_g :: Integer+    -- ^ the generator+    , pubkeyDH_q :: Integer+    -- ^ the prime factor of p-1+    , pubkeyDH_j :: Maybe Integer+    -- ^ the subgroup factor+    , pubkeyDH_validation :: Maybe (BitArray, Integer)+    -- ^ seed and pgenCounter+    , pubkeyDH_y :: Integer+    -- ^ the public value+    }+    deriving (Show, Eq)++-- | A DH public key from p, g, q and the public value, without j and+-- validation parameters.+dhPublicKey :: Integer -> Integer -> Integer -> Integer -> PubKeyDH+dhPublicKey p g q y = PubKeyDH_ p g q Nothing Nothing y+ -- | Public key types known and used in X.509 data PubKey     = -- | RSA public key       PubKeyRSA RSA.PublicKey+    | -- | RSASSA-PSS public key, restricted to the parameters if any+      PubKeyRSAPSS RSA.PublicKey (Maybe PSSParams)     | -- | DSA public key       PubKeyDSA DSA.PublicKey-    | -- | DH format with (p,g,q,j,(seed,pgenCounter))-      PubKeyDH (Integer, Integer, Integer, Maybe Integer, ([Word8], Integer))+    | -- | X9.42 DH public key+      PubKeyDH PubKeyDH     | -- | EC public key       PubKeyEC PubKeyEC     | -- | X25519 public key@@ -89,6 +125,12 @@       PubKeyMLDSA65 (MLDSA.VerificationKey MLDSA.MLDSA65)     | -- | ML-DSA-87 public key       PubKeyMLDSA87 (MLDSA.VerificationKey MLDSA.MLDSA87)+    | -- | ML-KEM-512 public key+      PubKeyMLKEM512 (MLKEM.EncapsulationKey MLKEM.MLKEM512)+    | -- | ML-KEM-768 public key+      PubKeyMLKEM768 (MLKEM.EncapsulationKey MLKEM.MLKEM768)+    | -- | ML-KEM-1024 public key+      PubKeyMLKEM1024 (MLKEM.EncapsulationKey MLKEM.MLKEM1024)     | -- | unrecognized format       PubKeyUnknown OID B.ByteString     deriving (Show, Eq)@@ -106,6 +148,12 @@             case removeNull xs of                 End Sequence : BitString bits : End Sequence : xs2 -> decodeASN1Err "RSA" bits xs2 (toPubKeyRSA . rsaPubFromASN1)                 _ -> Left ("fromASN1: X509.PubKey: unknown RSA format: " ++ show xs)+        | pkalg == getObjectID PubKeyALG_RSAPSS = do+            (mp, ys) <- pssKeyParamsFromASN1 xs+            case ys of+                BitString bits : End Sequence : xs2 ->+                    decodeASN1Err "RSA-PSS" bits xs2 (toPubKeyRSAPSS mp . rsaPubFromASN1)+                _ -> Left ("fromASN1: X509.PubKey: unknown RSA-PSS format: " ++ show xs)         | pkalg == getObjectID PubKeyALG_DSA =             case xs of                 Start Sequence : IntVal p : IntVal q : IntVal g : End Sequence : End Sequence@@ -132,6 +180,23 @@                                 _ -> Left "fromASN1: X509.PubKey: unknown DSA format"                             )                 _ -> Left "fromASN1: X509.PubKey: unknown DSA format"+        | pkalg == getObjectID PubKeyALG_DH =+            case xs of+                Start Sequence : IntVal p : IntVal g : IntVal q : rest ->+                    let (j, rest1) = case rest of+                            IntVal j' : r -> (Just j', r)+                            r -> (Nothing, r)+                        (v, rest2) = case rest1 of+                            Start Sequence : BitString seed : IntVal c : End Sequence : r ->+                                (Just (seed, c), r)+                            r -> (Nothing, r)+                     in case rest2 of+                            End Sequence : End Sequence : BitString bits : End Sequence : xs2 ->+                                decodeASN1Err "DH" bits xs2 $ \l -> case l of+                                    [IntVal y] -> Right (PubKeyDH (PubKeyDH_ p g q j v y), [])+                                    _ -> Left "fromASN1: X509.PubKey: unknown DH format"+                            _ -> Left "fromASN1: X509.PubKey: unknown DH format"+                _ -> Left "fromASN1: X509.PubKey: unknown DH format"         | pkalg == getObjectID PubKeyALG_EC =             case xs of                 OID curveOid : End Sequence : BitString bits : End Sequence : xs2 ->@@ -203,6 +268,21 @@             case xs of                 End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "ML-DSA-87" PubKeyMLDSA87 bits xs2 MLDSA.verificationKey                 _ -> Left ("fromASN1: X509.PubKey: unknown ML-DSA-87 format: " ++ show xs)+        | pkalg == getObjectID PubKeyALG_MLKEM512 =+            case xs of+                End Sequence : BitString bits : End Sequence : xs2 ->+                    decodeCF "ML-KEM-512" PubKeyMLKEM512 bits xs2 (MLKEM.encapsulationKey @MLKEM.MLKEM512)+                _ -> Left ("fromASN1: X509.PubKey: unknown ML-KEM-512 format: " ++ show xs)+        | pkalg == getObjectID PubKeyALG_MLKEM768 =+            case xs of+                End Sequence : BitString bits : End Sequence : xs2 ->+                    decodeCF "ML-KEM-768" PubKeyMLKEM768 bits xs2 (MLKEM.encapsulationKey @MLKEM.MLKEM768)+                _ -> Left ("fromASN1: X509.PubKey: unknown ML-KEM-768 format: " ++ show xs)+        | pkalg == getObjectID PubKeyALG_MLKEM1024 =+            case xs of+                End Sequence : BitString bits : End Sequence : xs2 ->+                    decodeCF "ML-KEM-1024" PubKeyMLKEM1024 bits xs2 (MLKEM.encapsulationKey @MLKEM.MLKEM1024)+                _ -> Left ("fromASN1: X509.PubKey: unknown ML-KEM-1024 format: " ++ show xs)         -- parameters of unknown algorithms are not kept         | otherwise = case dropParams (0 :: Int) xs of             BitString bits : End Sequence : xs2 ->@@ -226,6 +306,7 @@                     Right _ ->                         Left ("fromASN1: X509.PubKey " ++ format ++ " bitarray has trailing data")         toPubKeyRSA = either Left (\(rsaKey, r) -> Right (PubKeyRSA rsaKey, r))+        toPubKeyRSAPSS mp = either Left (\(rsaKey, r) -> Right (PubKeyRSAPSS rsaKey mp, r))          bitArrayToPoint = SerializedPoint . bitArrayGetData @@ -247,6 +328,7 @@ -- | Convert a Public key to the Public Key Algorithm type pubkeyToAlg :: PubKey -> PubKeyALG pubkeyToAlg (PubKeyRSA _) = PubKeyALG_RSA+pubkeyToAlg (PubKeyRSAPSS _ _) = PubKeyALG_RSAPSS pubkeyToAlg (PubKeyDSA _) = PubKeyALG_DSA pubkeyToAlg (PubKeyDH _) = PubKeyALG_DH pubkeyToAlg (PubKeyEC _) = PubKeyALG_EC@@ -257,6 +339,9 @@ pubkeyToAlg (PubKeyMLDSA44 _) = PubKeyALG_MLDSA44 pubkeyToAlg (PubKeyMLDSA65 _) = PubKeyALG_MLDSA65 pubkeyToAlg (PubKeyMLDSA87 _) = PubKeyALG_MLDSA87+pubkeyToAlg (PubKeyMLKEM512 _) = PubKeyALG_MLKEM512+pubkeyToAlg (PubKeyMLKEM768 _) = PubKeyALG_MLKEM768+pubkeyToAlg (PubKeyMLKEM1024 _) = PubKeyALG_MLKEM1024 pubkeyToAlg (PubKeyUnknown oid _) = PubKeyALG_Unknown oid  encodePK :: PubKey -> [ASN1]@@ -267,6 +352,10 @@         asn1Container Sequence [pkalg, Null] ++ [BitString $ toBitArray bits 0]       where         bits = encodeASN1' DER $ rsaPubToASN1 pubkey []+    encodeInner (PubKeyRSAPSS pubkey mp) =+        pssKeyAlgToASN1 mp [BitString $ toBitArray bits 0]+      where+        bits = encodeASN1' DER $ rsaPubToASN1 pubkey []     encodeInner (PubKeyDSA pubkey) =         asn1Container Sequence ([pkalg] ++ dsaseq) ++ [BitString $ toBitArray bits 0]       where@@ -321,7 +410,24 @@         asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]     encodeInner (PubKeyMLDSA87 pubkey) =         asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]-    encodeInner (PubKeyDH _) = error "encodeInner: unimplemented public key DH"+    encodeInner (PubKeyMLKEM512 pubkey) =+        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]+    encodeInner (PubKeyMLKEM768 pubkey) =+        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]+    encodeInner (PubKeyMLKEM1024 pubkey) =+        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]+    encodeInner (PubKeyDH k) =+        asn1Container Sequence ([pkalg] ++ params) ++ [BitString $ toBitArray bits 0]+      where+        params =+            asn1Container Sequence $+                [IntVal (pubkeyDH_p k), IntVal (pubkeyDH_g k), IntVal (pubkeyDH_q k)]+                    ++ maybe [] (\j -> [IntVal j]) (pubkeyDH_j k)+                    ++ maybe+                        []+                        (\(seed, c) -> asn1Container Sequence [BitString seed, IntVal c])+                        (pubkeyDH_validation k)+        bits = encodeASN1' DER [IntVal $ pubkeyDH_y k]     encodeInner (PubKeyUnknown _ l) =         asn1Container Sequence [pkalg, Null] ++ [BitString $ toBitArray l 0] 
+ Tests/MLKEMKeys.hs view
@@ -0,0 +1,105 @@+-- | An ML-KEM-512 key pair as OpenSSL 3.6 writes it, the private key in+-- the @both@ form of RFC 9935 Section 6.+--+--   openssl genpkey -algorithm ML-KEM-512 -outform DER+module MLKEMKeys (+    opensslMLKEM512,+    opensslMLKEM512Pub,+) where++import qualified Data.ByteString as BS++import Data.ByteArray.Encoding (Base (Base16), convertFromBase)++hex :: String -> BS.ByteString+hex s = case convertFromBase Base16 (BS.pack (map (fromIntegral . fromEnum) s)) of+    Left e -> error e+    Right b -> b++-- | The private key in PKCS #8, 1730 bytes of DER.+opensslMLKEM512 :: BS.ByteString+opensslMLKEM512 =+    hex $+        concat+            [ "308206be020100300b0609608648016503040401048206aa308206a60440303c9e9931"+            , "cf571d70c1a1bc9e3fee10bb20be3e48ce37752b3825a98b734afe86b9f1579f881312"+            , "c97924fdc6253630f4780c591a43833a7bfb4646fa67446504820660f9f7b203581c57"+            , "651a9877931c3ca3affbc4d3453294109d01a62c01303f26515a930012fd90506cc0ae"+            , "61280425c021644027fa9aab706c877b8a8fd978c0af83cd1b30cd5f983b46c35f25ab"+            , "8215caa7919766ae84283f622ea261366feb4d7683af23c62ff744aa6aa55598b9b462"+            , "b1bc0ca001a9f78386197b8d7958de569aa660958324c37cd17c02bac63d657bd2863d"+            , "84ea2104ab3402aaa55f4c1e062a40b62017048a0a8570397e43cf1a4a2d3451429e15"+            , "889478cd55e36eeeb822dd034f99d5760a15b220697f14e48a026a2800523ac9b645a4"+            , "075c73807094412fadb368fdc6ba207b18e61c64ff4cb8085357ae762495791973717f"+            , "960a69b3ab69bfb620aed7ce315acd8f8a6a8394ce471047c5ebb6bd7aa6258635b105"+            , "06e503794c4871cb524242568ff91aa2f8d243ee52c82e6a1e1228481e396f90dc3692"+            , "eaad9cb1ae7b6981e00c7e15f758db09b6bbc0833d9688431098b1589c77d925d2d281"+            , "2e008a7fca305d526acf0318370646918369b26a2590968c944c963b38945bd71442ca"+            , "18d09266237097067c7f3b493e14f72406a03462473b647c5d498424105c009da44f30"+            , "550c228b473b0bd0f1cc44960409d1321cd3135a85101d21c178d6f3c7c46c3a628b95"+            , "e4a84192b54582b7c6a57ac057aaaed1c650b357ac315486450029ff31671822c3927a"+            , "c20385c093b5b347203982912a6df44890abbe19368a694876fdb69f36f1a6b5967277"+            , "c4916959b242667085c21bb38397029a7674d55ae0216506fc36ed199113307472358e"+            , "52fbb0eac46f012500deb9bf5d0ba0c9f835d85bcb32f2bcff754516489eae9512dcfb"+            , "ae01214aa0baa6f228783b8c084b9b4f013a6a65f7991226213bb51d324b8ed6822ec8"+            , "d30b73f54b38585a30f08a87b193a2f3be9671bfcf430fee179a580717c0169e29d083"+            , "195c70a76ac8d288a1c7ba2c3ae952e0f227379149084b6b4fd29043505c5cf857f3a2"+            , "b15eb129a171c70e609954b63c9c8b91424a3e54d682e715b4fb16b49ab22f28873985"+            , "17007ca522ca2c59c9eaa345130b5f8893edd81ce343680f5b5941d3918a6492b0060b"+            , "918c0f40a1415d8c894c7ccfa9c508cc7caccba7b8d680074f6001fe81ca93534cf9d6"+            , "6d59d38f13c6c19e6c92fc8a688bf2b21fe4bc06a413fdb62422292a1da2c1a2791852"+            , "4ab698b655ea0425f1fa37b55c3478d9576cec866c302abd805f501abe622606aab049"+            , "022251e9a4bc1949aa0fdb11f5451c9537b1715279a7ab9a2c38227c168adbfc198bbc"+            , "133e520157ab02cb696bc3c082207b846f9a5c54c977619a58a93a4d8a869ed97043ed"+            , "39270adac530734281148639a848a0a484e174c95363c7f1373a62376724a2506b39a3"+            , "dbf125fdd75f3f0920bcd8b980c82e6da61b3bc60a83a722846c22f857ad4823174de1"+            , "cc1be652e9d1289e072da89aa2e534ad9b5a5fa6159f2d925dc385168b621541d86494"+            , "c16138d927ca48b5cad233f4c39f575b778f9302d98a5a6d45745b277f1146bf652011"+            , "98518bf9283aef42bf3ed269aea01c64481a0a773a2f95c31c8781465bc6a58270497b"+            , "633790bc780379278bce43eb958b25c6dd85806446bce93a2a5bdbae1b585054f900dc"+            , "08939e84a24db913c1857c3b75c388dbbad45172828a220a5a384822afaf3195f0c880"+            , "7380cfc2956e639696f96168f56334ee3a2eb6ea583bf99dd8336cf5176307f4687660"+            , "359fa74f0efc587562baf1440647f44b1c30710efcce0ec886523c4c91b12cab5552a0"+            , "b944c0ac3a6dbc887fd426eec64c011a975a979945c4a6e0d09d8800268f290c38128f"+            , "c3c0cc6734a527957c1d5322fca448f3a7932d934867e85b51c6a21b31c20f84777dac"+            , "780872c589ec4217b67e70557c94daa16deab210a3b6434190f07086b10129b9971f6a"+            , "fcce3aa64a2c8b89020c83fbf45178d866b4800216795688a30388044f811a1639c338"+            , "41c7983018760189263a708e16e12d83f1931ae6214208a98761c478a32b05798a810a"+            , "603ef66c6a4596f0783e5a20aae4455721c544a4a0b318c9aa70a99e131771bf6a897b"+            , "6b6057ccab21946ff17c4d6d6c288b3296be6338c12c1717cba126173e80d8c1d7d0a0"+            , "36758d43a24c9487526ac8326c0102149162f351b03c35928154d188153e80a8feaba0"+            , "c93c1f218ba11defc11e225423b86c27cb2b8bb1441d27e59f14a6f9c28d72e7bb064b"+            , "9f427078b2837876e1dd22f1f4b0bd4ff49086b9f1579f881312c97924fdc6253630f4"+            , "780c591a43833a7bfb4646fa674465"+            ]++-- | The public key in SubjectPublicKeyInfo, 822 bytes of DER.+opensslMLKEM512Pub :: BS.ByteString+opensslMLKEM512Pub =+    hex $+        concat+            [ "30820332300b0609608648016503040401038203210041d3918a6492b0060b918c0f40"+            , "a1415d8c894c7ccfa9c508cc7caccba7b8d680074f6001fe81ca93534cf9d66d59d38f"+            , "13c6c19e6c92fc8a688bf2b21fe4bc06a413fdb62422292a1da2c1a27918524ab698b6"+            , "55ea0425f1fa37b55c3478d9576cec866c302abd805f501abe622606aab049022251e9"+            , "a4bc1949aa0fdb11f5451c9537b1715279a7ab9a2c38227c168adbfc198bbc133e5201"+            , "57ab02cb696bc3c082207b846f9a5c54c977619a58a93a4d8a869ed97043ed39270ada"+            , "c530734281148639a848a0a484e174c95363c7f1373a62376724a2506b39a3dbf125fd"+            , "d75f3f0920bcd8b980c82e6da61b3bc60a83a722846c22f857ad4823174de1cc1be652"+            , "e9d1289e072da89aa2e534ad9b5a5fa6159f2d925dc385168b621541d86494c16138d9"+            , "27ca48b5cad233f4c39f575b778f9302d98a5a6d45745b277f1146bf65201198518bf9"+            , "283aef42bf3ed269aea01c64481a0a773a2f95c31c8781465bc6a58270497b633790bc"+            , "780379278bce43eb958b25c6dd85806446bce93a2a5bdbae1b585054f900dc08939e84"+            , "a24db913c1857c3b75c388dbbad45172828a220a5a384822afaf3195f0c8807380cfc2"+            , "956e639696f96168f56334ee3a2eb6ea583bf99dd8336cf5176307f4687660359fa74f"+            , "0efc587562baf1440647f44b1c30710efcce0ec886523c4c91b12cab5552a0b944c0ac"+            , "3a6dbc887fd426eec64c011a975a979945c4a6e0d09d8800268f290c38128fc3c0cc67"+            , "34a527957c1d5322fca448f3a7932d934867e85b51c6a21b31c20f84777dac780872c5"+            , "89ec4217b67e70557c94daa16deab210a3b6434190f07086b10129b9971f6afcce3aa6"+            , "4a2c8b89020c83fbf45178d866b4800216795688a30388044f811a1639c33841c79830"+            , "18760189263a708e16e12d83f1931ae6214208a98761c478a32b05798a810a603ef66c"+            , "6a4596f0783e5a20aae4455721c544a4a0b318c9aa70a99e131771bf6a897b6b6057cc"+            , "ab21946ff17c4d6d6c288b3296be6338c12c1717cba126173e80d8c1d7d0a036758d43"+            , "a24c9487526ac8326c0102149162f351b03c35928154d188153e80a8feaba0c93c1f21"+            , "8ba11defc11e225423b86c27cb2b8bb144"+            ]
Tests/Tests.hs view
@@ -20,6 +20,7 @@ import qualified Crypto.PubKey.Ed25519 as Ed25519 import qualified Crypto.PubKey.Ed448 as Ed448 import qualified Crypto.PubKey.MLDSA as MLDSA+import qualified Crypto.PubKey.MLKEM as MLKEM import qualified Crypto.PubKey.RSA as RSA import Data.ASN1.BinaryEncoding (DER (..)) import Data.ASN1.BitArray (toBitArray)@@ -33,6 +34,7 @@ import Data.X509.EC (ecPubKeyCurveName)  import MLDSAKeys+import MLKEMKeys  import Data.Hourglass @@ -70,7 +72,9 @@     arbitrary =         oneof             [ PubKeyRSA <$> arbitrary+            , PubKeyRSAPSS <$> arbitrary <*> arbitraryKeyPSS             , PubKeyDSA <$> arbitrary+            , PubKeyDH <$> arbitraryDH             , -- , PubKeyECDSA ECDSA_Hash_SHA384 <$> (B.pack <$> replicateM 384 arbitrary)               PubKeyX25519 <$> arbitrary             , PubKeyX448 <$> arbitrary@@ -79,8 +83,45 @@             , PubKeyMLDSA44 . MLDSA.toPublic <$> arbitraryMLDSA (Proxy :: Proxy MLDSA.MLDSA44)             , PubKeyMLDSA65 . MLDSA.toPublic <$> arbitraryMLDSA (Proxy :: Proxy MLDSA.MLDSA65)             , PubKeyMLDSA87 . MLDSA.toPublic <$> arbitraryMLDSA (Proxy :: Proxy MLDSA.MLDSA87)+            , PubKeyMLKEM512 . fst <$> arbitraryMLKEM (Proxy :: Proxy MLKEM.MLKEM512)+            , PubKeyMLKEM768 . fst <$> arbitraryMLKEM (Proxy :: Proxy MLKEM.MLKEM768)+            , PubKeyMLKEM1024 . fst <$> arbitraryMLKEM (Proxy :: Proxy MLKEM.MLKEM1024)             ] +arbitraryKeyPSS :: Gen (Maybe PSSParams)+arbitraryKeyPSS =+    oneof+        [ pure Nothing+        , (\h m s -> Just (defaultPSSParams h){pssMGFHash = m, pssSaltLength = s})+            <$> hash+            <*> hash+            <*> choose (0, 64)+        ]+  where+    hash =+        elements+            [ HashSHA1+            , HashSHA224+            , HashSHA256+            , HashSHA384+            , HashSHA512+            , HashSHA3_256+            , HashSHA3_512+            ]++arbitraryDH :: Gen PubKeyDH+arbitraryDH = do+    k <- dhPublicKey <$> pos <*> pos <*> pos <*> pos+    j <- oneof [pure Nothing, Just <$> pos]+    v <-+        oneof+            [ pure Nothing+            , (\s c -> Just (toBitArray (B.pack s) 0, c)) <$> arbitrary <*> pos+            ]+    return k{pubkeyDH_j = j, pubkeyDH_validation = v}+  where+    pos = getPositive <$> arbitrary+ instance Arbitrary RSA.PrivateKey where     arbitrary =         RSA.PrivateKey@@ -111,6 +152,7 @@     arbitrary =         oneof             [ PrivKeyRSA <$> arbitrary+            , PrivKeyRSAPSS <$> arbitrary <*> arbitraryKeyPSS             , PrivKeyDSA <$> arbitrary             , -- , PrivKeyECDSA ECDSA_Hash_SHA384 <$> (B.pack <$> replicateM 384 arbitrary)               PrivKeyX25519 <$> arbitrary@@ -120,8 +162,21 @@             , PrivKeyMLDSA44 <$> arbitraryPrivMLDSA (Proxy :: Proxy MLDSA.MLDSA44)             , PrivKeyMLDSA65 <$> arbitraryPrivMLDSA (Proxy :: Proxy MLDSA.MLDSA65)             , PrivKeyMLDSA87 <$> arbitraryPrivMLDSA (Proxy :: Proxy MLDSA.MLDSA87)+            , PrivKeyMLKEM512 <$> arbitraryPrivMLKEM (Proxy :: Proxy MLKEM.MLKEM512)+            , PrivKeyMLKEM768 <$> arbitraryPrivMLKEM (Proxy :: Proxy MLKEM.MLKEM768)+            , PrivKeyMLKEM1024 <$> arbitraryPrivMLKEM (Proxy :: Proxy MLKEM.MLKEM1024)             ] +arbitraryMLKEM+    :: MLKEM.MLKEM p+    => proxy p -> Gen (MLKEM.EncapsulationKey p, MLKEM.DecapsulationKey p)+arbitraryMLKEM p = throwCryptoError . MLKEM.keyPairFromSeed p <$> arbitraryBS 64 64++arbitraryPrivMLKEM :: MLKEM.MLKEM p => proxy p -> Gen (PrivKeyMLKEM p)+arbitraryPrivMLKEM p = do+    form <- elements [MLKeySeed, MLKeyExpanded, MLKeyBoth]+    throwCryptoError . privkeyMLKEMFromSeed p form <$> arbitraryBS 64 64+ arbitraryMLDSA :: MLDSA.MLDSA p => proxy p -> Gen (MLDSA.SigningKey p) arbitraryMLDSA p = snd . throwCryptoError . MLDSA.keyPairFromSeed p <$> arbitraryBS 32 32 @@ -129,13 +184,24 @@ -- covers each of them and not just whichever one this module would pick. arbitraryPrivMLDSA :: MLDSA.MLDSA p => proxy p -> Gen (PrivKeyMLDSA p) arbitraryPrivMLDSA p = do-    form <- elements [MLDSAKeySeed, MLDSAKeyExpanded, MLDSAKeyBoth]+    form <- elements [MLKeySeed, MLKeyExpanded, MLKeyBoth]     throwCryptoError . privkeyMLDSAFromSeed p form <$> arbitraryBS 32 32  instance Arbitrary HashALG where     arbitrary =         elements-            [HashMD2, HashMD5, HashSHA1, HashSHA224, HashSHA256, HashSHA384, HashSHA512]+            [ HashMD2+            , HashMD5+            , HashSHA1+            , HashSHA224+            , HashSHA256+            , HashSHA384+            , HashSHA512+            , HashSHA3_224+            , HashSHA3_256+            , HashSHA3_384+            , HashSHA3_512+            ]  instance Arbitrary PubKeyALG where     arbitrary = elements [PubKeyALG_RSA, PubKeyALG_DSA, PubKeyALG_EC, PubKeyALG_DH]@@ -160,6 +226,18 @@             , SignatureALG HashSHA256 PubKeyALG_EC             , SignatureALG HashSHA384 PubKeyALG_EC             , SignatureALG HashSHA512 PubKeyALG_EC+            , SignatureALG HashSHA3_224 PubKeyALG_RSA+            , SignatureALG HashSHA3_256 PubKeyALG_RSA+            , SignatureALG HashSHA3_384 PubKeyALG_RSA+            , SignatureALG HashSHA3_512 PubKeyALG_RSA+            , SignatureALG HashSHA3_224 PubKeyALG_DSA+            , SignatureALG HashSHA3_256 PubKeyALG_DSA+            , SignatureALG HashSHA3_384 PubKeyALG_DSA+            , SignatureALG HashSHA3_512 PubKeyALG_DSA+            , SignatureALG HashSHA3_224 PubKeyALG_EC+            , SignatureALG HashSHA3_256 PubKeyALG_EC+            , SignatureALG HashSHA3_384 PubKeyALG_EC+            , SignatureALG HashSHA3_512 PubKeyALG_EC             , SignatureALG_IntrinsicHash PubKeyALG_Ed25519             , SignatureALG_IntrinsicHash PubKeyALG_Ed448             , SignatureALG_IntrinsicHash PubKeyALG_MLDSA44@@ -329,12 +407,12 @@                 MLDSA.keyPairFromSeed (Proxy :: Proxy MLDSA.MLDSA44) seed  -- | The three encodings of one seed, with the form each of them is.-mldsaForms :: B.ByteString -> [(MLDSAKeyForm, [ASN1])]+mldsaForms :: B.ByteString -> [(MLKeyForm, [ASN1])] mldsaForms seed =-    [ (MLDSAKeySeed, [Other Context 0 seed])-    , (MLDSAKeyExpanded, [OctetString expanded])+    [ (MLKeySeed, [Other Context 0 seed])+    , (MLKeyExpanded, [OctetString expanded])     ,-        ( MLDSAKeyBoth+        ( MLKeyBoth         , [Start Sequence, OctetString seed, OctetString expanded, End Sequence]         )     ]@@ -384,7 +462,7 @@ property_mldsa_generated_seed :: Property property_mldsa_generated_seed = ioProperty $ do     (_, sk, seed) <- MLDSA.generateKeyPairAndSeed p-    let k = throwCryptoError $ privkeyMLDSAFromSeed p MLDSAKeySeed seed+    let k = throwCryptoError $ privkeyMLDSAFromSeed p MLKeySeed seed         privkey = PrivKeyMLDSA44 k         encoded = toASN1 privkey []     return $@@ -417,7 +495,7 @@         Left _ -> False         Right asn1 -> case fromASN1 asn1 :: Either String (PrivKey, [ASN1]) of             Right (k, []) ->-                formOf k == Just MLDSAKeyBoth+                formOf k == Just MLKeyBoth                     && encodeASN1' DER (toASN1 k []) == der             _ -> False     formOf (PrivKeyMLDSA44 k) = Just (privkeyMLDSA_form k)@@ -444,7 +522,7 @@          in not (hex seed `isInfixOf` shown)                 && not (expanded `isInfixOf` shown)                 && expanded `isInfixOf` debugged-                && (form == MLDSAKeyExpanded || hex seed `isInfixOf` debugged)+                && (form == MLKeyExpanded || hex seed `isInfixOf` debugged)  property_mldsa_mismatch :: MLDSASeed -> MLDSASeed -> Property property_mldsa_mismatch (MLDSASeed seed1) (MLDSASeed seed2) =@@ -465,9 +543,18 @@             , AltNameURI . ("https://" ++) <$> arbitraryHost             , AltNameIP . B.pack <$> (elements [4, 16] >>= vector)             , AltNameDN <$> arbitrary+            , AltNameOther <$> arbitraryOID <*> der+            , AltNameX400 <$> der+            , AltNameEDIParty <$> der+            , AltNameRegisteredID <$> arbitraryOID             ]       where         arbitraryHost = listOf1 (elements "abcxyz.-")+        der = (\n -> encodeASN1' DER [IntVal n]) <$> arbitrary+        arbitraryOID = do+            a <- choose (0, 2)+            b <- if a < 2 then choose (0, 39) else choose (0, 1000)+            (\xs -> a : b : xs) <$> listOf (getNonNegative <$> arbitrary)  instance Arbitrary GeneralSubtree where     arbitrary =@@ -486,13 +573,34 @@ instance Arbitrary ExtSubjectAltName where     arbitrary = ExtSubjectAltName <$> arbitrary -instance Arbitrary DistributionPoint where+instance Arbitrary ExtAuthorityKeyId where+    arbitrary = do+        k <- oneof [pure Nothing, Just . B.pack <$> listOf1 arbitrary]+        is <- oneof [pure Nothing, curry Just <$> listOf1 arbitrary <*> arbitrary]+        return defaultExtAuthorityKeyId{akiKeyIdentifier = k, akiIssuerSerial = is}++instance Arbitrary DistributionPointName where     arbitrary =         oneof             [ DistributionPointFullName <$> listOf1 arbitrary-            , DistributionNameRelative <$> arbitrary+            , DistributionPointRelativeName . concat . getRDNs+                <$> arbitrary `suchThat` (not . null . getRDNs)             ] +instance Arbitrary DistributionPoint where+    arbitrary = do+        name <- oneof [pure Nothing, Just <$> arbitrary]+        rs <-+            oneof+                [ pure Nothing+                , Just . nub . sort <$> listOf1 (elements [Reason_Unused .. Reason_AACompromise])+                ]+        issuer <- case name of+            Nothing -> Just <$> listOf1 arbitrary+            Just _ -> oneof [pure Nothing, Just <$> listOf1 arbitrary]+        return+            defaultDistributionPoint{dpName = name, dpReasons = rs, dpCRLIssuer = issuer}+ instance Arbitrary ExtCrlDistributionPoints where     arbitrary = ExtCrlDistributionPoints <$> listOf1 arbitrary @@ -540,27 +648,32 @@     isLeft = either (const True) (const False)  -- Unsupported GeneralName types in a SAN are skipped, but not in constraints.-property_san_skips_unknown :: Bool-property_san_skips_unknown =-    extDecode-        ( [Start Sequence]+property_san_keeps_names :: Bool+property_san_keeps_names =+    extDecode san == Right (ExtSubjectAltName names)+        && extEncode (ExtSubjectAltName names) == san+        && extDecode nc+            == Right+                (ExtNameConstraints [GeneralSubtree (AltNameRegisteredID [1, 2, 3]) 0 Nothing] [])+  where+    san =+        [Start Sequence]             ++ registeredID             ++ [Other Context 2 (B.pack [0x61])]             ++ otherName             ++ [Start (Container Context 4)]             ++ toASN1 dn [End (Container Context 4)]             ++ [End Sequence]-        )-        == Right (ExtSubjectAltName [AltNameDNS "a", AltNameDN dn])-        && isLeft-            ( extDecode-                ( [Start Sequence, Start (Container Context 0), Start Sequence]-                    ++ registeredID-                    ++ [End Sequence, End (Container Context 0), End Sequence]-                )-                :: Either String ExtNameConstraints-            )-  where+    names =+        [ AltNameRegisteredID [1, 2, 3]+        , AltNameDNS "a"+        , AltNameOther [1, 2, 3] (encodeASN1' DER [IntVal 1])+        , AltNameDN dn+        ]+    nc =+        [Start Sequence, Start (Container Context 0), Start Sequence]+            ++ registeredID+            ++ [End Sequence, End (Container Context 0), End Sequence]     dn = DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")]     registeredID = [Other Context 8 (B.pack [0x2a, 0x03])]     otherName =@@ -571,7 +684,6 @@         , End (Container Context 0)         , End (Container Context 0)         ]-    isLeft = either (const True) (const False)  -- A certificate whose validity cannot be decoded is rejected with 'Left' -- rather than an exception thrown lazily from the decoder.@@ -757,31 +869,40 @@  property_aki_issuer_serial :: Bool property_aki_issuer_serial =-    extDecode-        ( [Start Sequence, Other Context 0 kid, Start (Container Context 1)]-            ++ [Start (Container Context 4)]-            ++ toASN1-                (DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")])-                []-            ++ [End (Container Context 4), End (Container Context 1)]-            ++ [Other Context 2 (B.pack [1]), End Sequence]-        )-        == Right (ExtAuthorityKeyId kid)+    extDecode (aki [Other Context 0 kid] ++ issuer ++ serial ++ [End Sequence])+        == Right full+        && extDecode (aki issuer ++ serial ++ [End Sequence])+            == Right full{akiKeyIdentifier = Nothing}+        && isLeft'+            (extDecode (aki issuer ++ [End Sequence]) :: Either String ExtAuthorityKeyId)+        && case full of+            ExtAuthorityKeyId k -> k == kid+            _ -> False   where     kid = B.pack [1, 2, 3]+    dn = DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")]+    aki = (Start Sequence :)+    issuer =+        [Start (Container Context 1), Start (Container Context 4)]+            ++ toASN1 dn [End (Container Context 4), End (Container Context 1)]+    serial = [Other Context 2 (B.pack [0x80])]+    full =+        defaultExtAuthorityKeyId+            { akiKeyIdentifier = Just kid+            , akiIssuerSerial = Just ([AltNameDN dn], -128)+            } --- RSASSA-PSS keys (with parameters) and other unknown keys are kept as--- PubKeyUnknown.+-- Unknown keys are kept as PubKeyUnknown, with or without parameters. property_unknown_pubkey :: Bool property_unknown_pubkey =-    decode [] == Right (PubKeyUnknown pss key, [])-        && decode [Start Sequence, End Sequence] == Right (PubKeyUnknown pss key, [])+    decode [] == Right (PubKeyUnknown oid key, [])+        && decode [Start Sequence, End Sequence] == Right (PubKeyUnknown oid key, [])   where-    pss = [1, 2, 840, 113549, 1, 1, 10]+    oid = [1, 2, 3, 4]     key = B.pack [1, 2, 3]     decode params =         fromASN1-            ( [Start Sequence, Start Sequence, OID pss]+            ( [Start Sequence, Start Sequence, OID oid]                 ++ params                 ++ [End Sequence, BitString (toBitArray key 0), End Sequence]             )@@ -904,25 +1025,202 @@         , End Sequence         ] +-- An X9.42 DH public key generated by OpenSSL is decoded and re-encoded+-- unchanged.+property_dh_pubkey :: Bool+property_dh_pubkey =+    case decodeASN1' DER der of+        Right asn1 -> case fromASN1 asn1 of+            Right (k@(PubKeyDH dh), []) ->+                pubkeyDH_q dh > 0+                    && pubkeyDH_y dh > 0+                    && encodeASN1' DER (toASN1 k []) == der+            _ -> False+        Left _ -> False+  where+    der =+        hexToBS $+            concat+                [ "3081f03081a806072a8648ce3e020130819c024100bb138b0c2555252ccb4b53"+                , "b674eea6ddcb7bbcbee1a52a4aef642d021df8e5bb86d5f16fd18a5510250aab"+                , "c740387fc57ceccebe9c4509e071e3c770478c052702405e0a4adbc2ed9dff00"+                , "ab23d851587759c7e27b539edbabc88be100b9c42b305434f1ddc8c445ce80d6"+                , "02e541f94bd221c36190b043966cf3c7a518c3760d7aa1021500ababf77df37b"+                , "481355fece9e7b5385348518c507034300024071e43594903589cf9cbc096df8"+                , "bfc7c0c6f3a92500d08f00299971fa9e83415e015ae3d8df3f5f553a90c4eeda"+                , "41085409b1ffe2b9b16ff75315870528996f0c"+                ]+    hexToBS (a : b : r) = read ("0x" ++ [a, b]) `B.cons` hexToBS r+    hexToBS _ = B.empty++-- An RSASSA-PSS key pair generated by OpenSSL (SHA-256, MGF1 SHA-256,+-- salt 32) is parsed and encoded back to the same DER.+property_rsapss_key :: Bool+property_rsapss_key =+    case (decode pubDER, decode privDER) of+        ( Right (pub@(PubKeyRSAPSS k (Just p)), [])+            , Right (priv@(PrivKeyRSAPSS sk (Just p')), [])+            ) ->+                p == defaultPSSParams HashSHA256+                    && p' == p+                    && RSA.private_pub sk == k+                    && encodeASN1' DER (toASN1 pub []) == pubDER+                    && encodeASN1' DER (toASN1 priv []) == privDER+        _ -> False+  where+    decode :: ASN1Object a => B.ByteString -> Either String (a, [ASN1])+    decode bs = either (Left . show) fromASN1 (decodeASN1' DER bs)+    alg =+        "304106092a864886f70d01010a3034a00f300d06096086480165030402010500a11c301a"+            ++ "06092a864886f70d010108300d06096086480165030402010500a203020120"+    n =+        "be657c50fe582caf8b9c48bddcf1478f5d885e335c2053d8afee4a90c01e435a8340dff2"+            ++ "5c862be573f60b9c99a53ef92010ae866bfb778c7257f18bf228746102"+    pubDER = hexToBS $ "308190" ++ alg ++ "034b003048024100" ++ n ++ "03010001"+    privDER =+        hexToBS $+            concat+                [ "3082018a020100"+                , alg+                , "048201403082013c020100024100"+                , n+                , "0301000102404b111a3d98ba4d0bfd6065f1ad9dd797f7c99f52629d4051abb3a8e4"+                , "7f4aaf44de480b85bcd4a73bdb09c4b6f503c6ccdaf4702b39cf0e541e5a02ab4ab3"+                , "4801022100f76d88ad3a9d0e1ed1070a99015221565288617fcec45328115ecd387b"+                , "3b44c1022100c4fe222364d78291e0558a071342768cae8c7b0a2433cd4dac8955e3"+                , "e98cf7a1022100d82fbe520d7a9891d8755c8f1f965146894a5c563da5503b1c2247"+                , "1168aafa81022100addce6607ab642c5614bdde0d4bcca48ec1d8cd2ac9513d4443d"+                , "8a12f7a4b541022100aa4977e25992e372f53318407d440e5cbb7b329c9a31bdd45a"+                , "049ef22eb8a0bf"+                ]+    hexToBS (a : b : r) = read ("0x" ++ [a, b]) `B.cons` hexToBS r+    hexToBS _ = B.empty++-- An ML-KEM-512 key pair written by OpenSSL is read in the both form,+-- the public key matches the private key, and both encode back the same.+property_mlkem_openssl :: Bool+property_mlkem_openssl =+    case (decode opensslMLKEM512Pub, decode opensslMLKEM512) of+        (Right (pub@(PubKeyMLKEM512 ek), []), Right (priv@(PrivKeyMLKEM512 k), [])) ->+            privkeyMLKEM_form k == MLKeyBoth+                && fmap (fst . throwCryptoError . MLKEM.keyPairFromSeed p) (privkeyMLKEM_seed k)+                    == Just ek+                && privkeyToAlg priv == PubKeyALG_MLKEM512+                && encodeASN1' DER (toASN1 pub []) == opensslMLKEM512Pub+                && encodeASN1' DER (toASN1 priv []) == opensslMLKEM512+        _ -> False+  where+    p = Proxy :: Proxy MLKEM.MLKEM512+    decode :: ASN1Object a => B.ByteString -> Either String (a, [ASN1])+    decode bs = either (Left . show) fromASN1 (decodeASN1' DER bs)++-- Multi-valued RDNs are kept and differ from separate RDNs; the canonical+-- form ignores the order inside an RDN.+property_multi_valued_rdn :: Bool+property_multi_valued_rdn =+    decode (encode multi) == Right (multi, [])+        && encodeASN1' DER (encode multi) /= encodeASN1' DER (encode single)+        && multi /= single+        && getDistinguishedElements multi == getDistinguishedElements single+        && single == fromRDNs [[cn], [o]]+        && canonicalDistinguishedName multi+            == canonicalDistinguishedName (fromRDNs [[o, cn]])+        && getDnElement DnOrganization multi == Just (snd o)+  where+    cn = (getObjectID DnCommonName, asn1CharacterString UTF8 "a")+    o = (getObjectID DnOrganization, asn1CharacterString UTF8 "o")+    multi = fromRDNs [[cn, o]]+    single = DistinguishedName [cn, o]+    encode dn = toASN1 dn []+    decode l = fromASN1 l :: Either String (DistinguishedName, [ASN1])++-- Every DnElement maps to a distinct OID and back.+property_dn_element_oid :: Bool+property_dn_element_oid =+    all (\e -> fromObjectID (getObjectID e) == Just e) els+        && length (nub (map getObjectID els)) == length els+  where+    els = [minBound .. maxBound] :: [DnElement]++-- Non-default PSS parameters are kept, explicit defaults are normalized,+-- and trailer fields other than 1 are rejected.+property_pss_params :: Bool+property_pss_params =+    decode (pssAsn1 [hash sha384 0, mgf sha256, salt 0])+        == Right (SignatureALG_RSAPSS custom, [])+        && toASN1 (SignatureALG_RSAPSS custom) []+            == pssAsn1 [hash sha384 0, mgf sha256, salt 0]+        && rsaPSSSignatureALG custom == SignatureALG_RSAPSS custom+        && signatureALGPSSParams (SignatureALG_RSAPSS custom) == Just custom+        && decode (pssAsn1 [hash sha1 0, mgf sha1, salt 20])+            == Right (SignatureALG HashSHA1 PubKeyALG_RSAPSS, [])+        && rsaPSSSignatureALG (defaultPSSParams HashSHA256)+            == SignatureALG HashSHA256 PubKeyALG_RSAPSS+        && decode (pssAsn1 [noNull (hash sha384 0), noNull (mgf sha256), salt 0])+            == Right (SignatureALG_RSAPSS custom, [])+        && isLeft'+            ( decode+                (pssAsn1 [[Start (Container Context 3), IntVal 2, End (Container Context 3)]])+            )+  where+    noNull = filter (/= Null)+    custom = (defaultPSSParams HashSHA384){pssMGFHash = HashSHA256, pssSaltLength = 0}+    sha1 = [1, 3, 14, 3, 2, 26]+    sha256 = [2, 16, 840, 1, 101, 3, 4, 2, 1]+    sha384 = [2, 16, 840, 1, 101, 3, 4, 2, 2]+    decode l = fromASN1 l :: Either String (SignatureALG, [ASN1])+    ctx n l = Start (Container Context n) : l ++ [End (Container Context n)]+    hash h n = ctx n [Start Sequence, OID h, Null, End Sequence]+    mgf h =+        ctx+            1+            [ Start Sequence+            , OID [1, 2, 840, 113549, 1, 1, 8]+            , Start Sequence+            , OID h+            , Null+            , End Sequence+            , End Sequence+            ]+    salt n = ctx 2 [IntVal n]+    pssAsn1 fields =+        [Start Sequence, OID [1, 2, 840, 113549, 1, 1, 10], Start Sequence]+            ++ concat fields+            ++ [End Sequence, End Sequence]+ -- The usual form (as written by OpenSSL), and points with reasons and a--- cRLIssuer, whose name only is kept, or without a name, which are dropped.+-- cRLIssuer, or with a cRLIssuer only, are kept; a point with neither a+-- name nor a cRLIssuer is rejected. property_crl_dp_der :: Bool property_crl_dp_der =-    extensionDecode (ExtensionRaw [2, 5, 29, 31] False der)-        == Just-            (Right (ExtCrlDistributionPoints [DistributionPointFullName [AltNameURI url]]))-        && extEncodeBs-            (ExtCrlDistributionPoints [DistributionPointFullName [AltNameURI url]])-            == der+    extensionDecode (ExtensionRaw [2, 5, 29, 31] False der) == Just (Right simple)+        && extEncodeBs simple == der         && extDecode             ( [Start Sequence]                 ++ dp (uriName ++ [Other Context 1 (B.pack [6, 0x40])] ++ issuer)                 ++ dp issuer                 ++ [End Sequence]             )-            == Right (ExtCrlDistributionPoints [DistributionPointFullName [AltNameURI url]])+            == Right+                ( ExtCrlDistributionPoints+                    [ uriDP+                        { dpReasons = Just [Reason_KeyCompromise]+                        , dpCRLIssuer = Just [AltNameDNS "a"]+                        }+                    , defaultDistributionPoint{dpCRLIssuer = Just [AltNameDNS "a"]}+                    ]+                )+        && isLeft'+            ( extDecode ([Start Sequence] ++ dp [] ++ [End Sequence])+                :: Either String ExtCrlDistributionPoints+            )   where     url = "http://crl.example.com/ca.crl"+    uriDP =+        defaultDistributionPoint+            { dpName = Just (DistributionPointFullName [AltNameURI url])+            }+    simple = ExtCrlDistributionPoints [uriDP]     der =         B.pack             ( [0x30, 0x25, 0x30, 0x23, 0xa0, 0x21, 0xa0, 0x1f, 0x86, 0x1d]@@ -952,7 +1250,8 @@ -- Per-family AlgorithmIdentifier parameters contract: -- ECDSA (RFC 5758 3.2, RFC 3279 2.2.3) and DSA (RFC 5758 3.1, RFC 3279 -- 2.2.2) omit the parameters field; RSA PKCS#1 v1.5 encodes an ASN.1--- NULL (RFC 3279 2.2.1); EdDSA omits the field (RFC 8410 3).+-- NULL (RFC 3279 2.2.1, RFC 9688 3.1 for SHA-3); EdDSA omits the field+-- (RFC 8410 3). property_sig_alg_parameters :: SignatureALG -> Bool property_sig_alg_parameters alg@(SignatureALG _ pub)     | pub == PubKeyALG_EC || pub == PubKeyALG_DSA = Null `notElem` toASN1 alg []@@ -982,6 +1281,9 @@                         "subject-alt-name"                         (property_extension_id :: ExtSubjectAltName -> Bool)                     , testProperty+                        "authority-key-id"+                        (property_extension_id :: ExtAuthorityKeyId -> Bool)+                    , testProperty                         "crl-distribution-points"                         (property_extension_id :: ExtCrlDistributionPoints -> Bool)                     , testProperty "crl-distribution-points-der" property_crl_dp_der@@ -994,7 +1296,7 @@                     "malformed"                     [ testProperty "key-usage unknown bits" property_key_usage_unknown_bits                     , testProperty "extensions" property_malformed_extensions-                    , testProperty "SAN skips unknown names" property_san_skips_unknown+                    , testProperty "SAN keeps all name forms" property_san_keeps_names                     , testProperty "lazy decode error" property_lazy_decode_error                     , testProperty "signed object" property_signed_strict                     , testProperty "duplicate extensions" property_duplicate_extensions@@ -1013,6 +1315,12 @@                     , testProperty "validity time" property_validity_time                     , testProperty "v1 CRL" property_crl_v1                     , testProperty "PSS default parameters" property_pss_default+                    , testProperty "PSS parameters" property_pss_params+                    , testProperty "multi-valued RDN" property_multi_valued_rdn+                    , testProperty "DN element OID" property_dn_element_oid+                    , testProperty "DH public key" property_dh_pubkey+                    , testProperty "RSASSA-PSS key" property_rsapss_key+                    , testProperty "ML-KEM OpenSSL key" property_mlkem_openssl                     , testProperty "EC private key length" property_ec_privkey_length                     , testProperty "EC curve name" property_ec_curve_name                     ]
crypton-x509.cabal view
@@ -1,6 +1,6 @@ cabal-version:      >=1.10 name:               crypton-x509-version:            1.10.3+version:            1.11.0 license:            BSD3 license-file:       LICENSE copyright:          Vincent Hanquez <vincent@snarc.org>@@ -44,7 +44,7 @@         base >=4.7 && <5,         bytestring,         containers,-        crypton >=2.1.8 && <2.3,+        crypton >=2.1.8 && <2.4,         crypton-asn1-encoding >=0.10.0 && <0.11,         crypton-asn1-parse >=0.10.0 && <0.11,         crypton-asn1-types >=0.4.1 && <0.5,@@ -56,7 +56,9 @@ test-suite test-x509     type:             exitcode-stdio-1.0     main-is:          Tests.hs-    other-modules:    MLDSAKeys+    other-modules:+        MLDSAKeys+        MLKEMKeys     hs-source-dirs:   Tests     default-language: Haskell2010     ghc-options:      -Wall -fno-warn-orphans -fno-warn-missing-signatures