crypton-x509 1.7.7 → 1.11.0
raw patch · 20 files changed
Files
- ChangeLog.md +99/−0
- Data/X509.hs +95/−57
- Data/X509/AlgorithmIdentifier.hs +291/−75
- Data/X509/CRL.hs +59/−54
- Data/X509/Cert.hs +106/−79
- Data/X509/CertificateChain.hs +17/−15
- Data/X509/DistinguishedName.hs +140/−42
- Data/X509/EC.hs +54/−46
- Data/X509/Ext.hs +580/−188
- Data/X509/ExtensionRaw.hs +46/−26
- Data/X509/Internal.hs +74/−10
- Data/X509/OID.hs +40/−42
- Data/X509/PrivateKey.hs +722/−155
- Data/X509/PublicKey.hs +385/−165
- Data/X509/Signed.hs +131/−94
- Setup.hs +1/−0
- Tests/MLDSAKeys.hs +365/−0
- Tests/MLKEMKeys.hs +105/−0
- Tests/Tests.hs +1358/−222
- crypton-x509.cabal +73/−61
+ ChangeLog.md view
@@ -0,0 +1,99 @@+# 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,+duplicate extensions or trailing data are rejected.++* Omit AlgorithmIdentifier parameters for ECDSA and DSA signatures+ [#32](https://github.com/kazu-yamamoto/crypton-certificate/pull/32)+* Make certificate parsing stricter+ [#39](https://github.com/kazu-yamamoto/crypton-certificate/pull/39)+* Accept and encode valid structures in crypton-x509+ [#46](https://github.com/kazu-yamamoto/crypton-certificate/pull/46)+* Build certification paths with backtracking and implement CRL distribution points+ [#48](https://github.com/kazu-yamamoto/crypton-certificate/pull/48)+* Small fixes for EC keys, RSA verification and EKU+ [#50](https://github.com/kazu-yamamoto/crypton-certificate/pull/50)++## 1.10.2++* Reject iPAddress GeneralNames of invalid length in SubjectAltName+ (4 or 16 bytes) and NameConstraints (8 or 32 bytes).++## 1.10.1++* Decoding functions return `Left` instead of throwing on malformed+ input (lazy decoder errors, unknown key usage bits, non-OID extended+ key usage, CRL distribution points, invalid strings).+* Fix the encoding of NameConstraints, which its own decoder could not+ read, and of directoryName and dNSSRV GeneralNames.+* SubjectAltName decoding skips unsupported GeneralName types.++## 1.10.0++* Support ML-DSA (RFC 9881)+ [#35](https://github.com/kazu-yamamoto/crypton-certificate/pull/35)+* An ML-DSA private key keeps the form it was written in+ [#35](https://github.com/kazu-yamamoto/crypton-certificate/pull/35)++## 1.9.2++* Stop printing EC private keys+ [#34](https://github.com/kazu-yamamoto/crypton-certificate/pull/34)++## 1.9.1++* Implementing the X509 name constrains extension.+ [#30](https://github.com/kazu-yamamoto/crypton-certificate/pull/30)++## 1.9.0++* Using "ram" instead of "memory"+ [#29](https://github.com/kazu-yamamoto/crypton-certificate/pull/29)++## 1.8.0++* Depend on package `time-hourglass`, rather than `hourglass`. Date and+ time-related types and classes are now those from the former package.+ [#18](https://github.com/kazu-yamamoto/crypton-certificate/pull/18)+* Depend on package `crypton-asn1-types >= 0.4.1` rather than `asn1-types`.+ ASN.1-related types and classes are now those from the former package.++## 1.7.7++* Bump requirements to GHC 7.8 and transformers 0.4 series+ [#130](https://github.com/haskell-tls/hs-certificate/pull/130)
Data/X509.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE PatternSynonyms #-}+ -- | -- Module : Data.X509 -- License : BSD-style@@ -8,75 +10,102 @@ -- Read/Write X509 Certificate, CRL and their signed equivalents. -- -- Follows RFC5280 / RFC6818----module Data.X509- (+module Data.X509 ( -- * Types- SignedCertificate- , SignedCRL- , Certificate(..)- , PubKey(..)- , PubKeyEC(..)- , SerializedPoint(..)- , PrivKey(..)- , PrivKeyEC(..)- , pubkeyToAlg- , privkeyToAlg- , module Data.X509.AlgorithmIdentifier- , module Data.X509.Ext- , module Data.X509.ExtensionRaw+ SignedCertificate,+ SignedCRL,+ Certificate (..),+ PubKey (..),+ PubKeyEC (..),+ PubKeyDH,+ dhPublicKey,+ pubkeyDH_p,+ pubkeyDH_g,+ pubkeyDH_q,+ pubkeyDH_j,+ pubkeyDH_validation,+ pubkeyDH_y,+ SerializedPoint (..),+ PrivKey (..),+ PrivKeyEC (..),+ PrivKeyMLDSA,+ 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,+ module Data.X509.Ext,+ module Data.X509.ExtensionRaw, -- * Certificate Revocation List (CRL)- , module Data.X509.CRL+ module Data.X509.CRL, -- * Naming- , DistinguishedName(..)- , DnElement(..)- , ASN1CharacterString(..)- , getDnElement+ DistinguishedName (DistinguishedName, getDistinguishedElements),+ RelativeDistinguishedName,+ getRDNs,+ fromRDNs,+ DnElement (..),+ ASN1CharacterString (..),+ getDnElement,+ canonicalDistinguishedName, -- * Certificate Chain- , module Data.X509.CertificateChain+ module Data.X509.CertificateChain, -- * Signed types and marshalling- , Signed(..)- , SignedExact- , getSigned- , getSignedData- , objectToSignedExact- , objectToSignedExactF- , encodeSignedObject- , decodeSignedObject+ Signed (..),+ SignedExact,+ getSigned,+ getSignedData,+ objectToSignedExact,+ objectToSignedExactF,+ encodeSignedObject,+ decodeSignedObject, -- * Parametrized Signed accessor- , getCertificate- , getCRL- , decodeSignedCertificate- , decodeSignedCRL+ getCertificate,+ getCRL,+ decodeSignedCertificate,+ decodeSignedCRL, -- * Hash distinguished names related function- , hashDN- , hashDN_old- ) where+ hashDN,+ hashDN_old,+) where import Control.Arrow (second) -import Data.ASN1.Types-import Data.ASN1.Encoding import Data.ASN1.BinaryEncoding-import qualified Data.ByteString as B+import Data.ASN1.Encoding+import Data.ASN1.Types import qualified Data.ByteArray as BA+import qualified Data.ByteString as B -import Data.X509.Cert-import Data.X509.Ext-import Data.X509.ExtensionRaw+import Data.X509.AlgorithmIdentifier hiding (pssKeyAlgToASN1, pssKeyParamsFromASN1) import Data.X509.CRL+import Data.X509.Cert import Data.X509.CertificateChain import Data.X509.DistinguishedName-import Data.X509.Signed-import Data.X509.PublicKey+import Data.X509.Ext+import Data.X509.ExtensionRaw import Data.X509.PrivateKey-import Data.X509.AlgorithmIdentifier+import Data.X509.PublicKey+import Data.X509.Signed import Crypto.Hash @@ -84,7 +113,7 @@ type SignedCertificate = SignedExact Certificate -- | A Signed CRL-type SignedCRL = SignedExact CRL+type SignedCRL = SignedExact CRL -- | Get the Certificate associated to a SignedCertificate getCertificate :: SignedCertificate -> Certificate@@ -107,19 +136,28 @@ -- OpenSSL algorithm is odd, and has been replicated here somewhat. -- only lower the case of ascii character. hashDN :: DistinguishedName -> B.ByteString-hashDN = shorten . hashWith SHA1 . encodeASN1' DER . flip toASN1 [] . DistinguishedNameInner . dnLowerUTF8- where dnLowerUTF8 (DistinguishedName l) = DistinguishedName $ map (second toLowerUTF8) l- toLowerUTF8 (ASN1CharacterString _ s) = ASN1CharacterString UTF8 (B.map asciiToLower s)- asciiToLower c- | c >= w8A && c <= w8Z = fromIntegral (fromIntegral c - fromEnum 'A' + fromEnum 'a')- | otherwise = c- w8A = fromIntegral $ fromEnum 'A'- w8Z = fromIntegral $ fromEnum 'Z'+hashDN =+ shorten+ . hashWith SHA1+ . encodeASN1' DER+ . flip toASN1 []+ . DistinguishedNameInner+ . dnLowerUTF8+ where+ dnLowerUTF8 = fromRDNs . map (map (second toLowerUTF8)) . getRDNs+ toLowerUTF8 (ASN1CharacterString _ s) = ASN1CharacterString UTF8 (B.map asciiToLower s)+ asciiToLower c+ | c >= w8A && c <= w8Z =+ fromIntegral (fromIntegral c - fromEnum 'A' + fromEnum 'a')+ | otherwise = c+ w8A = fromIntegral $ fromEnum 'A'+ w8Z = fromIntegral $ fromEnum 'Z' -- | Create an openssl style old hash of distinguished name hashDN_old :: DistinguishedName -> B.ByteString hashDN_old = shorten . hashWith MD5 . encodeASN1' DER . flip toASN1 [] shorten :: Digest a -> B.ByteString-shorten b = B.pack $ map i [3,2,1,0]- where i n = BA.index b n+shorten b = B.pack $ map i [3, 2, 1, 0]+ where+ i n = BA.index b n
Data/X509/AlgorithmIdentifier.hs view
@@ -4,117 +4,333 @@ -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown----module Data.X509.AlgorithmIdentifier- ( HashALG(..)- , PubKeyALG(..)- , SignatureALG(..)- ) where+module Data.X509.AlgorithmIdentifier (+ HashALG (..),+ PubKeyALG (..),+ SignatureALG (..),+ PSSParams,+ pssHash,+ pssMGFHash,+ pssSaltLength,+ defaultPSSParams,+ rsaPSSSignatureALG,+ signatureALGPSSParams, + -- * Internal+ pssKeyParamsFromASN1,+ pssKeyAlgToASN1,+) where+ import Data.ASN1.Types import Data.List (find) -- | Hash Algorithm-data HashALG =- HashMD2+data HashALG+ = HashMD2 | HashMD5 | HashSHA1 | HashSHA224 | HashSHA256 | HashSHA384 | HashSHA512- deriving (Show,Eq)+ | HashSHA3_224+ | HashSHA3_256+ | HashSHA3_384+ | HashSHA3_512+ deriving (Show, Eq) -- | Public Key Algorithm-data PubKeyALG =- PubKeyALG_RSA -- ^ RSA Public Key algorithm- | PubKeyALG_RSAPSS -- ^ RSA PSS Key algorithm (RFC 3447)- | PubKeyALG_DSA -- ^ DSA Public Key algorithm- | PubKeyALG_EC -- ^ ECDSA & ECDH Public Key algorithm- | PubKeyALG_X25519 -- ^ ECDH 25519 key agreement- | PubKeyALG_X448 -- ^ ECDH 448 key agreement- | PubKeyALG_Ed25519 -- ^ EdDSA 25519 signature algorithm- | PubKeyALG_Ed448 -- ^ EdDSA 448 signature algorithm- | PubKeyALG_DH -- ^ Diffie Hellman Public Key algorithm- | PubKeyALG_Unknown OID -- ^ Unknown Public Key algorithm- deriving (Show,Eq)+data PubKeyALG+ = -- | RSA Public Key algorithm+ PubKeyALG_RSA+ | -- | RSA PSS Key algorithm (RFC 3447)+ PubKeyALG_RSAPSS+ | -- | DSA Public Key algorithm+ PubKeyALG_DSA+ | -- | ECDSA & ECDH Public Key algorithm+ PubKeyALG_EC+ | -- | ECDH 25519 key agreement+ PubKeyALG_X25519+ | -- | ECDH 448 key agreement+ PubKeyALG_X448+ | -- | EdDSA 25519 signature algorithm+ PubKeyALG_Ed25519+ | -- | EdDSA 448 signature algorithm+ PubKeyALG_Ed448+ | -- | ML-DSA-44 signature algorithm (RFC 9881)+ PubKeyALG_MLDSA44+ | -- | ML-DSA-65 signature algorithm (RFC 9881)+ 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+ PubKeyALG_Unknown OID+ deriving (Show, Eq) -- | Signature Algorithm, often composed of a public key algorithm and a hash -- algorithm. For some signature algorithms the hash algorithm is intrinsic to -- the public key algorithm and is not needed in the data type.-data SignatureALG =- SignatureALG HashALG PubKeyALG+data SignatureALG+ = SignatureALG HashALG PubKeyALG | SignatureALG_IntrinsicHash PubKeyALG | SignatureALG_Unknown OID- deriving (Show,Eq)+ | -- | 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]- getObjectID PubKeyALG_DSA = [1,2,840,10040,4,1]- getObjectID PubKeyALG_EC = [1,2,840,10045,2,1]- getObjectID PubKeyALG_X25519 = [1,3,101,110]- getObjectID PubKeyALG_X448 = [1,3,101,111]- getObjectID PubKeyALG_Ed25519 = [1,3,101,112]- getObjectID PubKeyALG_Ed448 = [1,3,101,113]- getObjectID PubKeyALG_DH = [1,2,840,10046,2,1]+ getObjectID PubKeyALG_RSA = [1, 2, 840, 113549, 1, 1, 1]+ getObjectID PubKeyALG_RSAPSS = [1, 2, 840, 113549, 1, 1, 10]+ getObjectID PubKeyALG_DSA = [1, 2, 840, 10040, 4, 1]+ getObjectID PubKeyALG_EC = [1, 2, 840, 10045, 2, 1]+ getObjectID PubKeyALG_X25519 = [1, 3, 101, 110]+ getObjectID PubKeyALG_X448 = [1, 3, 101, 111]+ getObjectID PubKeyALG_Ed25519 = [1, 3, 101, 112]+ getObjectID PubKeyALG_Ed448 = [1, 3, 101, 113]+ 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 -sig_table :: [ (OID, SignatureALG) ]+sig_table :: [(OID, SignatureALG)] sig_table =- [ ([1,2,840,113549,1,1,5], SignatureALG HashSHA1 PubKeyALG_RSA)- , ([1,2,840,113549,1,1,4], SignatureALG HashMD5 PubKeyALG_RSA)- , ([1,2,840,113549,1,1,2], SignatureALG HashMD2 PubKeyALG_RSA)- , ([1,2,840,113549,1,1,11], SignatureALG HashSHA256 PubKeyALG_RSA)- , ([1,2,840,113549,1,1,12], SignatureALG HashSHA384 PubKeyALG_RSA)- , ([1,2,840,113549,1,1,13], SignatureALG HashSHA512 PubKeyALG_RSA)- , ([1,2,840,113549,1,1,14], SignatureALG HashSHA224 PubKeyALG_RSA)- , ([1,2,840,10040,4,3], SignatureALG HashSHA1 PubKeyALG_DSA)- , ([1,2,840,10045,4,1], SignatureALG HashSHA1 PubKeyALG_EC)- , ([1,2,840,10045,4,3,1], SignatureALG HashSHA224 PubKeyALG_EC)- , ([1,2,840,10045,4,3,2], SignatureALG HashSHA256 PubKeyALG_EC)- , ([1,2,840,10045,4,3,3], SignatureALG HashSHA384 PubKeyALG_EC)- , ([1,2,840,10045,4,3,4], SignatureALG HashSHA512 PubKeyALG_EC)- , ([2,16,840,1,101,3,4,2,1], SignatureALG HashSHA256 PubKeyALG_RSAPSS)- , ([2,16,840,1,101,3,4,2,2], SignatureALG HashSHA384 PubKeyALG_RSAPSS)- , ([2,16,840,1,101,3,4,2,3], SignatureALG HashSHA512 PubKeyALG_RSAPSS)- , ([2,16,840,1,101,3,4,2,4], SignatureALG HashSHA224 PubKeyALG_RSAPSS)- , ([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)- , ([1,3,101,112], SignatureALG_IntrinsicHash PubKeyALG_Ed25519)- , ([1,3,101,113], SignatureALG_IntrinsicHash PubKeyALG_Ed448)- ]+ [ ([1, 2, 840, 113549, 1, 1, 5], SignatureALG HashSHA1 PubKeyALG_RSA)+ , ([1, 2, 840, 113549, 1, 1, 4], SignatureALG HashMD5 PubKeyALG_RSA)+ , ([1, 2, 840, 113549, 1, 1, 2], SignatureALG HashMD2 PubKeyALG_RSA)+ , ([1, 2, 840, 113549, 1, 1, 11], SignatureALG HashSHA256 PubKeyALG_RSA)+ , ([1, 2, 840, 113549, 1, 1, 12], SignatureALG HashSHA384 PubKeyALG_RSA)+ , ([1, 2, 840, 113549, 1, 1, 13], SignatureALG HashSHA512 PubKeyALG_RSA)+ , ([1, 2, 840, 113549, 1, 1, 14], SignatureALG HashSHA224 PubKeyALG_RSA)+ , ([1, 2, 840, 10040, 4, 3], SignatureALG HashSHA1 PubKeyALG_DSA)+ , ([1, 2, 840, 10045, 4, 1], SignatureALG HashSHA1 PubKeyALG_EC)+ , ([1, 2, 840, 10045, 4, 3, 1], SignatureALG HashSHA224 PubKeyALG_EC)+ , ([1, 2, 840, 10045, 4, 3, 2], SignatureALG HashSHA256 PubKeyALG_EC)+ , ([1, 2, 840, 10045, 4, 3, 3], SignatureALG HashSHA384 PubKeyALG_EC)+ , ([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)+ ,+ ( [2, 16, 840, 1, 101, 3, 4, 3, 17]+ , SignatureALG_IntrinsicHash PubKeyALG_MLDSA44+ )+ ,+ ( [2, 16, 840, 1, 101, 3, 4, 3, 18]+ , SignatureALG_IntrinsicHash PubKeyALG_MLDSA65+ )+ ,+ ( [2, 16, 840, 1, 101, 3, 4, 3, 19]+ , SignatureALG_IntrinsicHash PubKeyALG_MLDSA87+ )+ ] +-- | Hash algorithms in RSASSA-PSS parameters.+pssHashTable :: [(OID, HashALG)]+pssHashTable =+ [ ([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+pssHashOID h =+ maybe (error ("unknown PSS hash " ++ show h)) fst $+ find ((==) h . snd) pssHashTable+ oidSig :: OID -> SignatureALG oidSig oid = maybe (SignatureALG_Unknown oid) id $ lookup oid sig_table sigOID :: SignatureALG -> OID sigOID (SignatureALG_Unknown oid) = oid-sigOID sig = maybe (error ("unknown OID for " ++ show sig)) fst $ find ((==) sig . snd) sig_table+sigOID sig =+ 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] +-- | 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) =+ fromASN1 (Start Sequence : OID oid : Null : End Sequence : xs) = case oidSig oid of SignatureALG_IntrinsicHash _ ->- Left "fromASN1: X509.SignatureALG: EdDSA requires absent parameter"+ Left "fromASN1: X509.SignatureALG: EdDSA and ML-DSA require absent parameter" signatureAlg -> Right (signatureAlg, xs)- fromASN1 (Start Sequence:OID oid:End Sequence: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 _:Start Sequence:OID hash1:End Sequence:End _:Start _:Start Sequence:OID [1,2,840,113549,1,1,8]:Start Sequence:OID _hash2:End Sequence:End Sequence:End _:Start _: IntVal _iv: End _: End Sequence : End Sequence:xs) =- Right (oidSig hash1, xs)- fromASN1 (Start Sequence:OID [1,2,840,113549,1,1,10]:Start Sequence:Start _:Start Sequence:OID hash1:Null:End Sequence:End _:Start _:Start Sequence:OID [1,2,840,113549,1,1,8]:Start Sequence:OID _hash2:Null:End Sequence:End Sequence:End _:Start _: IntVal _iv: End _: End Sequence : End Sequence:xs) =- Right (oidSig hash1, 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@(SignatureALG hashAlg PubKeyALG_RSAPSS) = \xs -> Start Sequence:OID [1,2,840,113549,1,1,10]:Start Sequence:Start (Container Context 0):Start Sequence:OID (sigOID signatureAlg):End Sequence:End (Container Context 0):Start (Container Context 1): Start Sequence:OID [1,2,840,113549,1,1,8]:Start Sequence:OID (sigOID signatureAlg):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@(SignatureALG_IntrinsicHash _) = \xs -> Start Sequence:OID (sigOID signatureAlg):End Sequence:xs- toASN1 signatureAlg = \xs -> Start Sequence:OID (sigOID signatureAlg):Null:End Sequence:xs+ toASN1 (SignatureALG_Unknown oid) = \xs -> Start Sequence : OID oid : Null : 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)+ toASN1 signatureAlg@(SignatureALG _ PubKeyALG_EC) = \xs -> Start Sequence : OID (sigOID signatureAlg) : End Sequence : xs+ -- DSA: "the encoding SHALL omit the parameters field"+ -- (RFC 5758 3.1, RFC 3279 2.2.2)+ toASN1 signatureAlg@(SignatureALG _ PubKeyALG_DSA) = \xs -> Start Sequence : OID (sigOID signatureAlg) : End Sequence : xs+ toASN1 signatureAlg = \xs -> Start Sequence : OID (sigOID signatureAlg) : Null : End Sequence : xs
Data/X509/CRL.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE FlexibleContexts #-}+ -- | -- Module : Data.X509.CRL -- License : BSD-style@@ -8,89 +10,91 @@ -- Read and Write X509 Certificate Revocation List (CRL). -- -- follows RFC5280 / RFC6818.----{-# LANGUAGE FlexibleContexts #-}--module Data.X509.CRL- ( CRL(..)- , RevokedCertificate(..)- ) where--import Control.Applicative+module Data.X509.CRL (+ CRL (..),+ RevokedCertificate (..),+) where -import Data.Hourglass (DateTime, TimezoneOffset(..)) import Data.ASN1.Types+import Data.Hourglass (DateTime) -import Data.X509.DistinguishedName import Data.X509.AlgorithmIdentifier+import Data.X509.DistinguishedName import Data.X509.ExtensionRaw import Data.X509.Internal -- | Describe a Certificate revocation list data CRL = CRL- { crlVersion :: Integer- , crlSignatureAlg :: SignatureALG- , crlIssuer :: DistinguishedName- , crlThisUpdate :: DateTime- , crlNextUpdate :: Maybe DateTime+ { crlVersion :: Integer+ , crlSignatureAlg :: SignatureALG+ , crlIssuer :: DistinguishedName+ , crlThisUpdate :: DateTime+ , crlNextUpdate :: Maybe DateTime , crlRevokedCertificates :: [RevokedCertificate]- , crlExtensions :: Extensions- } deriving (Show,Eq)+ , crlExtensions :: Extensions+ }+ deriving (Show, Eq) -- | Describe a revoked certificate identifiable by serial number. data RevokedCertificate = RevokedCertificate { revokedSerialNumber :: Integer- , revokedDate :: DateTime- , revokedExtensions :: Extensions- } deriving (Show,Eq)+ , revokedDate :: DateTime+ , revokedExtensions :: Extensions+ }+ deriving (Show, Eq) instance ASN1Object CRL where toASN1 crl = encodeCRL crl fromASN1 = runParseASN1State parseCRL instance ASN1Object RevokedCertificate where- fromASN1 = runParseASN1State $- onNextContainer Sequence $- RevokedCertificate- <$> parseSerialNumber- <*> (getNext >>= toTime)- <*> getObject- where toTime (ASN1Time _ t _) = pure t- toTime _ = throwParseError "bad revocation date"+ fromASN1 =+ runParseASN1State $+ onNextContainer Sequence $+ RevokedCertificate+ <$> parseSerialNumber+ <*> (getNext >>= toTime)+ <*> getObject+ where+ toTime (ASN1Time _ t z) = pure (asn1TimeToUTC t z)+ toTime _ = throwParseError "bad revocation date" toASN1 (RevokedCertificate serial time crlEntryExtensions) = \xs ->- [ Start Sequence ] ++- [ IntVal serial ] ++- [ ASN1Time TimeGeneralized time (Just (TimezoneOffset 0)) ] ++- toASN1 crlEntryExtensions [] ++- [ End Sequence ] ++- xs+ [Start Sequence]+ ++ [IntVal serial]+ ++ [encodeASN1Time time]+ ++ toASN1 crlEntryExtensions []+ ++ [End Sequence]+ ++ xs parseSerialNumber :: ParseASN1 Integer parseSerialNumber = do n <- getNext case n of IntVal v -> return v- _ -> throwParseError ("missing serial" ++ show n)+ _ -> throwParseError ("missing serial" ++ show n) parseCRL :: ParseASN1 CRL parseCRL = do- CRL <$> (getNext >>= getVersion)+ CRL+ -- the version is absent in v1 CRLs+ <$> (maybe 0 id <$> getNextMaybe getVersion) <*> getObject <*> getObject <*> (getNext >>= getThisUpdate) <*> getNextUpdate <*> parseRevokedCertificates <*> parseCRLExtensions- where getVersion (IntVal v) = return $ fromIntegral v- getVersion _ = throwParseError "unexpected type for version"+ where+ getVersion (IntVal v) = Just v+ getVersion _ = Nothing - getThisUpdate (ASN1Time _ t1 _) = return t1- getThisUpdate _ = throwParseError "bad this update format, expecting time"+ getThisUpdate (ASN1Time _ t1 z) = return (asn1TimeToUTC t1 z)+ getThisUpdate _ = throwParseError "bad this update format, expecting time" - getNextUpdate = getNextMaybe timeOrNothing+ getNextUpdate = getNextMaybe timeOrNothing - timeOrNothing (ASN1Time _ tnext _) = Just tnext- timeOrNothing _ = Nothing+ timeOrNothing (ASN1Time _ tnext z) = Just (asn1TimeToUTC tnext z)+ timeOrNothing _ = Nothing parseRevokedCertificates :: ParseASN1 [RevokedCertificate] parseRevokedCertificates =@@ -99,19 +103,20 @@ parseCRLExtensions :: ParseASN1 Extensions parseCRLExtensions = fmap adapt $ onNextContainerMaybe (Container Context 0) $ getObject- where adapt (Just e) = e- adapt Nothing = Extensions Nothing+ where+ adapt (Just e) = e+ adapt Nothing = Extensions Nothing encodeCRL :: CRL -> ASN1S encodeCRL crl xs =- [IntVal $ crlVersion crl] ++- toASN1 (crlSignatureAlg crl) [] ++- toASN1 (crlIssuer crl) [] ++- [ASN1Time TimeGeneralized (crlThisUpdate crl) (Just (TimezoneOffset 0))] ++- (maybe [] (\t -> [ASN1Time TimeGeneralized t (Just (TimezoneOffset 0))]) (crlNextUpdate crl)) ++- maybeRevoked (crlRevokedCertificates crl) ++- maybeCrlExts (crlExtensions crl) ++- xs+ [IntVal (crlVersion crl) | crlVersion crl /= 0]+ ++ toASN1 (crlSignatureAlg crl) []+ ++ toASN1 (crlIssuer crl) []+ ++ [encodeASN1Time (crlThisUpdate crl)]+ ++ maybe [] (\t -> [encodeASN1Time t]) (crlNextUpdate crl)+ ++ maybeRevoked (crlRevokedCertificates crl)+ ++ maybeCrlExts (crlExtensions crl)+ ++ xs where maybeRevoked [] = [] maybeRevoked xs' = asn1Container Sequence $ concatMap (\e -> toASN1 e []) xs'
Data/X509/Cert.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE FlexibleContexts #-}+ -- | -- Module : Data.X509.Cert -- License : BSD-style@@ -6,118 +8,143 @@ -- Portability : unknown -- -- X.509 Certificate types and functions----{-# LANGUAGE FlexibleContexts #-}--module Data.X509.Cert (Certificate(..)) where+module Data.X509.Cert (Certificate (..)) where import Data.ASN1.Types-import Control.Applicative ((<$>), (<*>))-import Data.X509.Internal-import Data.X509.PublicKey+import Data.Hourglass import Data.X509.AlgorithmIdentifier import Data.X509.DistinguishedName import Data.X509.ExtensionRaw-import Data.Hourglass+import Data.X509.Internal+import Data.X509.PublicKey -data CertKeyUsage =- CertKeyUsageDigitalSignature- | CertKeyUsageNonRepudiation- | CertKeyUsageKeyEncipherment- | CertKeyUsageDataEncipherment- | CertKeyUsageKeyAgreement- | CertKeyUsageKeyCertSign- | CertKeyUsageCRLSign- | CertKeyUsageEncipherOnly- | CertKeyUsageDecipherOnly- deriving (Show, Eq)+data CertKeyUsage+ = CertKeyUsageDigitalSignature+ | CertKeyUsageNonRepudiation+ | CertKeyUsageKeyEncipherment+ | CertKeyUsageDataEncipherment+ | CertKeyUsageKeyAgreement+ | CertKeyUsageKeyCertSign+ | CertKeyUsageCRLSign+ | CertKeyUsageEncipherOnly+ | CertKeyUsageDecipherOnly+ deriving (Show, Eq) -- | X.509 Certificate type. -- -- This type doesn't include the signature, it's describe in the RFC -- as tbsCertificate. data Certificate = Certificate- { certVersion :: Int -- ^ Version- , certSerial :: Integer -- ^ Serial number- , certSignatureAlg :: SignatureALG -- ^ Signature algorithm- , certIssuerDN :: DistinguishedName -- ^ Issuer DN- , certValidity :: (DateTime, DateTime) -- ^ Validity period (UTC)- , certSubjectDN :: DistinguishedName -- ^ Subject DN- , certPubKey :: PubKey -- ^ Public key- , certExtensions :: Extensions -- ^ Extensions- } deriving (Show,Eq)+ { certVersion :: Int+ -- ^ Version+ , certSerial :: Integer+ -- ^ Serial number+ , certSignatureAlg :: SignatureALG+ -- ^ Signature algorithm+ , certIssuerDN :: DistinguishedName+ -- ^ Issuer DN+ , certValidity :: (DateTime, DateTime)+ -- ^ Validity period (UTC)+ , certSubjectDN :: DistinguishedName+ -- ^ Subject DN+ , certPubKey :: PubKey+ -- ^ Public key+ , certExtensions :: Extensions+ -- ^ Extensions+ }+ deriving (Show, Eq) instance ASN1Object Certificate where- toASN1 certificate = \xs -> encodeCertificateHeader certificate ++ xs- fromASN1 s = runParseASN1State parseCertificate s+ toASN1 certificate = \xs -> encodeCertificateHeader certificate ++ xs+ fromASN1 s = runParseASN1State parseCertificate s parseCertHeaderVersion :: ParseASN1 Int parseCertHeaderVersion = maybe 0 id <$> onNextContainerMaybe (Container Context 0) (getNext >>= getVer)- where getVer (IntVal v) = return $ fromIntegral v- getVer _ = throwParseError "unexpected type for version"+ where+ getVer (IntVal v)+ | v >= 0 && v <= 2 = return $ fromIntegral v+ | otherwise = throwParseError ("unsupported version " ++ show v)+ getVer _ = throwParseError "unexpected type for version" parseCertHeaderSerial :: ParseASN1 Integer parseCertHeaderSerial = do n <- getNext case n of IntVal v -> return v- _ -> throwParseError ("missing serial" ++ show n)+ _ -> throwParseError ("missing serial" ++ show n) parseCertHeaderValidity :: ParseASN1 (DateTime, DateTime) parseCertHeaderValidity = getNextContainer Sequence >>= toTimeBound- where toTimeBound [ ASN1Time _ t1 _, ASN1Time _ t2 _ ] = return (t1,t2)- toTimeBound _ = throwParseError "bad validity format"--{- | parse header structure of a x509 certificate. the structure is the following:- Version- Serial Number- Algorithm ID- Issuer- Validity- Not Before- Not After- Subject- Subject Public Key Info- Public Key Algorithm- Subject Public Key- Issuer Unique Identifier (Optional) (>= 2)- Subject Unique Identifier (Optional) (>= 2)- Extensions (Optional) (>= v3)--}+ where+ toTimeBound [ASN1Time _ t1 z1, ASN1Time _ t2 z2] =+ return (asn1TimeToUTC t1 z1, asn1TimeToUTC t2 z2)+ toTimeBound _ = throwParseError "bad validity format" +-- | parse header structure of a x509 certificate. the structure is the following:+-- Version+-- Serial Number+-- Algorithm ID+-- Issuer+-- Validity+-- Not Before+-- Not After+-- Subject+-- Subject Public Key Info+-- Public Key Algorithm+-- Subject Public Key+-- Issuer Unique Identifier (Optional) (>= 2)+-- Subject Unique Identifier (Optional) (>= 2)+-- Extensions (Optional) (>= v3) parseExtensions :: ParseASN1 Extensions parseExtensions = fmap adapt $ onNextContainerMaybe (Container Context 3) $ getObject- where adapt (Just e) = e- adapt Nothing = Extensions Nothing+ where+ adapt (Just e) = e+ adapt Nothing = Extensions Nothing +-- | issuerUniqueID and subjectUniqueID are skipped.+parseUniqueIDs :: ParseASN1 ()+parseUniqueIDs = uid 1 >> uid 2 >> return ()+ where+ uid n = getNextMaybe (\a -> if isUID n a then Just () else Nothing)+ isUID n (Other Context m _) = n == m+ isUID _ _ = False+ parseCertificate :: ParseASN1 Certificate parseCertificate =- Certificate <$> parseCertHeaderVersion- <*> parseCertHeaderSerial- <*> getObject- <*> getObject- <*> parseCertHeaderValidity- <*> getObject- <*> getObject- <*> parseExtensions+ Certificate+ <$> parseCertHeaderVersion+ <*> parseCertHeaderSerial+ <*> getObject+ <*> getObject+ <*> parseCertHeaderValidity+ <*> getObject+ <*> (getObject <* parseUniqueIDs)+ <*> parseExtensions encodeCertificateHeader :: Certificate -> [ASN1] encodeCertificateHeader cert =- eVer ++ eSerial ++ eAlgId ++ eIssuer ++ eValidity ++ eSubject ++ epkinfo ++ eexts- where eVer = asn1Container (Container Context 0) [IntVal (fromIntegral $ certVersion cert)]- eSerial = [IntVal $ certSerial cert]- eAlgId = toASN1 (certSignatureAlg cert) []- eIssuer = toASN1 (certIssuerDN cert) []- (t1, t2) = certValidity cert- eValidity = asn1Container Sequence [ASN1Time (timeType t1) t1 (Just (TimezoneOffset 0))- ,ASN1Time (timeType t2) t2 (Just (TimezoneOffset 0))]- eSubject = toASN1 (certSubjectDN cert) []- epkinfo = toASN1 (certPubKey cert) []- eexts = case certExtensions cert of- Extensions Nothing -> []- exts -> asn1Container (Container Context 3) $ toASN1 exts []- timeType t =- if t >= timeConvert (Date 2050 January 1)- then TimeGeneralized- else TimeUTC+ eVer+ ++ eSerial+ ++ eAlgId+ ++ eIssuer+ ++ eValidity+ ++ eSubject+ ++ epkinfo+ ++ eexts+ where+ eVer =+ asn1Container (Container Context 0) [IntVal (fromIntegral $ certVersion cert)]+ eSerial = [IntVal $ certSerial cert]+ eAlgId = toASN1 (certSignatureAlg cert) []+ eIssuer = toASN1 (certIssuerDN cert) []+ (t1, t2) = certValidity cert+ eValidity =+ asn1Container+ Sequence+ [encodeASN1Time t1, encodeASN1Time t2]+ eSubject = toASN1 (certSubjectDN cert) []+ epkinfo = toASN1 (certPubKey cert) []+ eexts = case certExtensions cert of+ Extensions Nothing -> []+ exts -> asn1Container (Container Context 3) $ toASN1 exts []
Data/X509/CertificateChain.hs view
@@ -4,37 +4,39 @@ -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown----module Data.X509.CertificateChain- ( CertificateChain(..)- , CertificateChainRaw(..)+module Data.X509.CertificateChain (+ CertificateChain (..),+ CertificateChainRaw (..),+ -- * marshall between CertificateChain and CertificateChainRaw- , decodeCertificateChain- , encodeCertificateChain- ) where+ decodeCertificateChain,+ encodeCertificateChain,+) where +import Data.ByteString (ByteString) import Data.X509.Cert (Certificate) import Data.X509.Signed (SignedExact, decodeSignedObject, encodeSignedObject)-import Data.ByteString (ByteString) -- | A chain of X.509 certificates in exact form. newtype CertificateChain = CertificateChain [SignedExact Certificate]- deriving (Show,Eq)+ deriving (Show, Eq) -- | Represent a chain of X.509 certificates in bytestring form. newtype CertificateChainRaw = CertificateChainRaw [ByteString]- deriving (Show,Eq)+ deriving (Show, Eq) -- | Decode a CertificateChainRaw into a CertificateChain if every -- raw certificate are decoded correctly, otherwise return the index of the -- failed certificate and the error associated.-decodeCertificateChain :: CertificateChainRaw -> Either (Int, String) CertificateChain+decodeCertificateChain+ :: CertificateChainRaw -> Either (Int, String) CertificateChain decodeCertificateChain (CertificateChainRaw l) = either Left (Right . CertificateChain) $ loop 0 l- where loop _ [] = Right []- loop i (r:rs) = case decodeSignedObject r of- Left err -> Left (i, err)- Right o -> either Left (Right . (o :)) $ loop (i+1) rs+ where+ loop _ [] = Right []+ loop i (r : rs) = case decodeSignedObject r of+ Left err -> Left (i, err)+ Right o -> either Left (Right . (o :)) $ loop (i + 1) rs -- | Convert a CertificateChain into a CertificateChainRaw encodeCertificateChain :: CertificateChain -> CertificateChainRaw
Data/X509/DistinguishedName.hs view
@@ -1,3 +1,7 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}+ -- | -- Module : Data.X509.DistinguishedName -- License : BSD-style@@ -6,92 +10,186 @@ -- Portability : unknown -- -- X.509 Distinguished names types and functions--{-# LANGUAGE CPP #-}-module Data.X509.DistinguishedName- ( DistinguishedName(..)- , DistinguishedNameInner(..)- , ASN1CharacterString(..)+module Data.X509.DistinguishedName (+ DistinguishedName (DistinguishedName, getDistinguishedElements),+ RelativeDistinguishedName,+ getRDNs,+ fromRDNs,+ DistinguishedNameInner (..),+ ASN1CharacterString (..), -- Distinguished Name Elements- , DnElement(..)- , getDnElement- ) where+ DnElement (..),+ getDnElement,+ canonicalDistinguishedName,+) where -import Control.Applicative-#if MIN_VERSION_base(4,9,0)+#if !(MIN_VERSION_base(4,11,0)) import Data.Semigroup-#else-import Data.Monoid #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)] }- deriving (Show,Eq,Ord)+-- | 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 =- DnCommonName -- ^ CN- | DnCountry -- ^ Country- | DnOrganization -- ^ O- | DnOrganizationUnit -- ^ OU- | DnEmailAddress -- ^ Email Address (legacy)- deriving (Show,Eq)+data DnElement+ = -- | CN+ DnCommonName+ | -- | Country+ DnCountry+ | -- | O+ DnOrganization+ | -- | OU+ DnOrganizationUnit+ | -- | Email Address (legacy)+ DnEmailAddress+ | -- | 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]- getObjectID DnCountry = [2,5,4,6]- getObjectID DnOrganization = [2,5,4,10]- getObjectID DnOrganizationUnit = [2,5,4,11]- getObjectID DnEmailAddress = [1,2,840,113549,1,9,1]+ getObjectID DnCommonName = [2, 5, 4, 3]+ getObjectID DnCountry = [2, 5, 4, 6]+ 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, and the+-- attributes of each RDN are sorted. Values+-- that cannot be decoded are kept.+canonicalDistinguishedName :: DistinguishedName -> DistinguishedName+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+ Nothing -> v+ -- | Only use to encode a DistinguishedName without including it in a -- Sequence newtype DistinguishedNameInner = DistinguishedNameInner DistinguishedName- deriving (Show,Eq)+ deriving (Show, Eq) #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 toASN1 dn = \xs -> encodeDN dn ++ xs- fromASN1 = runParseASN1State parseDN+ fromASN1 = runParseASN1State parseDN -- FIXME parseDNInner in fromASN1 is probably wrong as we don't have a container -- and thus hasNext should be replaced by a isFinished clause. instance ASN1Object DistinguishedNameInner where toASN1 (DistinguishedNameInner dn) = \xs -> encodeDNinner dn ++ xs- fromASN1 = runParseASN1State (DistinguishedNameInner . DistinguishedName <$> parseDNInner)+ fromASN1 =+ 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 [OID oid, ASN1String cs] -> return (oid, cs)- _ -> throwParseError ("expecting [OID,String] got " ++ show s)+ _ ->+ throwParseError ("expecting [OID,String] got " ++ show s) encodeDNinner :: DistinguishedName -> [ASN1]-encodeDNinner (DistinguishedName dn) = concatMap dnSet dn- where dnSet (oid, cs) = asn1Container Set $ asn1Container Sequence [OID oid, ASN1String cs]+encodeDNinner (RDNSequence rdns) = concatMap rdnSet rdns+ where+ 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/EC.hs view
@@ -6,27 +6,25 @@ -- Portability : unknown -- -- Utilities related to Elliptic Curve certificates and keys.----module Data.X509.EC- (- unserializePoint- , ecPubKeyCurve- , ecPubKeyCurveName- , ecPrivKeyCurve- , ecPrivKeyCurveName- , lookupCurveNameByOID- ) where+module Data.X509.EC (+ unserializePoint,+ ecPubKeyCurve,+ ecPubKeyCurveName,+ ecPrivKeyCurve,+ ecPrivKeyCurveName,+ lookupCurveNameByOID,+) where import Data.ASN1.OID import Data.List (find) import Data.X509.OID-import Data.X509.PublicKey import Data.X509.PrivateKey+import Data.X509.PublicKey -import qualified Crypto.PubKey.ECC.Prim as ECC+import Crypto.Number.Serialize (os2ip)+import qualified Crypto.PubKey.ECC.Prim as ECC import qualified Crypto.PubKey.ECC.Types as ECC-import Crypto.Number.Serialize (os2ip) import qualified Data.ByteString as B @@ -35,91 +33,101 @@ unserializePoint :: ECC.Curve -> SerializedPoint -> Maybe ECC.Point unserializePoint curve (SerializedPoint bs) = case B.uncons bs of- Nothing -> Nothing+ Nothing -> Nothing Just (ptFormat, input) -> case ptFormat of- 4 -> if B.length input /= 2 * bytes+ 4 ->+ if B.length input /= 2 * bytes then Nothing else let (x, y) = B.splitAt bytes input- p = ECC.Point (os2ip x) (os2ip y)+ p = ECC.Point (os2ip x) (os2ip y) in if ECC.isPointValid curve p then Just p else Nothing -- 2 and 3 for compressed format. _ -> Nothing- where bits = ECC.curveSizeBits curve- bytes = (bits + 7) `div` 8+ where+ bits = ECC.curveSizeBits curve+ bytes = (bits + 7) `div` 8 -- | Return the curve associated to an EC Public Key. This does not check -- if a curve in explicit format is valid: if the input is not trusted one -- should consider 'ecPubKeyCurveName' instead. ecPubKeyCurve :: PubKeyEC -> Maybe ECC.Curve ecPubKeyCurve (PubKeyEC_Named name _) = Just $ ECC.getCurveByName name-ecPubKeyCurve pub@PubKeyEC_Prime{} =+ecPubKeyCurve pub@PubKeyEC_Prime{} = fmap buildCurve $ unserializePoint (buildCurve undefined) (pubkeyEC_generator pub) where prime = pubkeyEC_prime pub buildCurve g =- let cc = ECC.CurveCommon- { ECC.ecc_a = pubkeyEC_a pub- , ECC.ecc_b = pubkeyEC_b pub- , ECC.ecc_g = g- , ECC.ecc_n = pubkeyEC_order pub- , ECC.ecc_h = pubkeyEC_cofactor pub- }+ let cc =+ ECC.CurveCommon+ { ECC.ecc_a = pubkeyEC_a pub+ , ECC.ecc_b = pubkeyEC_b pub+ , ECC.ecc_g = g+ , ECC.ecc_n = pubkeyEC_order pub+ , ECC.ecc_h = pubkeyEC_cofactor pub+ } in ECC.CurveFP (ECC.CurvePrime prime cc) -- | Return the name of a standard curve associated to an EC Public Key ecPubKeyCurveName :: PubKeyEC -> Maybe ECC.CurveName ecPubKeyCurveName (PubKeyEC_Named name _) = Just name-ecPubKeyCurveName pub@PubKeyEC_Prime{} =+ecPubKeyCurveName pub@PubKeyEC_Prime{} = find matchPrimeCurve $ enumFrom $ toEnum 0 where matchPrimeCurve c = case ECC.getCurveByName c of ECC.CurveFP (ECC.CurvePrime p cc) ->- ECC.ecc_a cc == pubkeyEC_a pub &&- ECC.ecc_b cc == pubkeyEC_b pub &&- ECC.ecc_n cc == pubkeyEC_order pub &&- p == pubkeyEC_prime pub- _ -> False+ ECC.ecc_a cc == pubkeyEC_a pub+ && ECC.ecc_b cc == pubkeyEC_b pub+ && ECC.ecc_n cc == pubkeyEC_order pub+ && ECC.ecc_h cc == pubkeyEC_cofactor pub+ && p == pubkeyEC_prime pub+ && unserializePoint (ECC.getCurveByName c) (pubkeyEC_generator pub)+ == Just (ECC.ecc_g cc)+ _ -> False -- | Return the EC curve associated to an EC Private Key. This does not check -- if a curve in explicit format is valid: if the input is not trusted one -- should consider 'ecPrivKeyCurveName' instead. ecPrivKeyCurve :: PrivKeyEC -> Maybe ECC.Curve ecPrivKeyCurve (PrivKeyEC_Named name _) = Just $ ECC.getCurveByName name-ecPrivKeyCurve priv@PrivKeyEC_Prime{} =+ecPrivKeyCurve priv@PrivKeyEC_Prime{} = fmap buildCurve $ unserializePoint (buildCurve undefined) (privkeyEC_generator priv) where prime = privkeyEC_prime priv buildCurve g =- let cc = ECC.CurveCommon- { ECC.ecc_a = privkeyEC_a priv- , ECC.ecc_b = privkeyEC_b priv- , ECC.ecc_g = g- , ECC.ecc_n = privkeyEC_order priv- , ECC.ecc_h = privkeyEC_cofactor priv- }+ let cc =+ ECC.CurveCommon+ { ECC.ecc_a = privkeyEC_a priv+ , ECC.ecc_b = privkeyEC_b priv+ , ECC.ecc_g = g+ , ECC.ecc_n = privkeyEC_order priv+ , ECC.ecc_h = privkeyEC_cofactor priv+ } in ECC.CurveFP (ECC.CurvePrime prime cc) -- | Return the name of a standard curve associated to an EC Private Key ecPrivKeyCurveName :: PrivKeyEC -> Maybe ECC.CurveName ecPrivKeyCurveName (PrivKeyEC_Named name _) = Just name-ecPrivKeyCurveName priv@PrivKeyEC_Prime{} =+ecPrivKeyCurveName priv@PrivKeyEC_Prime{} = find matchPrimeCurve $ enumFrom $ toEnum 0 where matchPrimeCurve c = case ECC.getCurveByName c of ECC.CurveFP (ECC.CurvePrime p cc) ->- ECC.ecc_a cc == privkeyEC_a priv &&- ECC.ecc_b cc == privkeyEC_b priv &&- ECC.ecc_n cc == privkeyEC_order priv &&- p == privkeyEC_prime priv- _ -> False+ ECC.ecc_a cc == privkeyEC_a priv+ && ECC.ecc_b cc == privkeyEC_b priv+ && ECC.ecc_n cc == privkeyEC_order priv+ && ECC.ecc_h cc == privkeyEC_cofactor priv+ && p == privkeyEC_prime priv+ && unserializePoint (ECC.getCurveByName c) (privkeyEC_generator priv)+ == Just (ECC.ecc_g cc)+ _ -> False -- | Return the curve name associated to an OID lookupCurveNameByOID :: OID -> Maybe ECC.CurveName
Data/X509/Ext.hs view
@@ -1,3 +1,8 @@+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE ViewPatterns #-}+ -- | -- Module : Data.X509.Ext -- License : BSD-style@@ -6,58 +11,70 @@ -- Portability : unknown -- -- extension processing module.----{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE ScopedTypeVariables #-}-module Data.X509.Ext- ( Extension(..)+module Data.X509.Ext (+ Extension (..),+ -- * Common extension usually found in x509v3- , ExtBasicConstraints(..)- , ExtKeyUsage(..)- , ExtKeyUsageFlag(..)- , ExtExtendedKeyUsage(..)- , ExtKeyUsagePurpose(..)- , ExtSubjectKeyId(..)- , ExtSubjectAltName(..)- , ExtAuthorityKeyId(..)- , ExtCrlDistributionPoints(..)- , ExtNetscapeComment(..)- , AltName(..)- , DistributionPoint(..)- , ReasonFlag(..)+ ExtBasicConstraints (..),+ ExtKeyUsage (..),+ ExtKeyUsageFlag (..),+ ExtExtendedKeyUsage (..),+ ExtKeyUsagePurpose (..),+ ExtSubjectKeyId (..),+ ExtSubjectAltName (..),+ ExtAuthorityKeyId (ExtAuthorityKeyId),+ defaultExtAuthorityKeyId,+ akiKeyIdentifier,+ akiIssuerSerial,+ ExtCrlDistributionPoints (..),+ ExtNetscapeComment (..),+ ExtNameConstraints (..),+ GeneralSubtree (..),+ AltName (..),+ DistributionPoint,+ defaultDistributionPoint,+ dpName,+ dpReasons,+ dpCRLIssuer,+ DistributionPointName (..),+ ReasonFlag (..),+ -- * Accessor turning extension into a specific one- , extensionGet- , extensionGetE- , extensionDecode- , extensionEncode- ) where+ extensionGet,+ extensionGetE,+ extensionDecode,+ extensionEncode,+ recognizedOIDs,+) where -import qualified Data.ByteString as B-import qualified Data.ByteString.Char8 as BC-import Data.ASN1.Types-import Data.ASN1.Parse-import Data.ASN1.Encoding+import Control.Monad import Data.ASN1.BinaryEncoding import Data.ASN1.BitArray-import Data.Proxy+import Data.ASN1.Encoding+import Data.ASN1.Parse+import Data.ASN1.Types+import Data.Bits (bit, shiftR, testBit, (.&.), (.|.))+import qualified Data.ByteString as B+import qualified Data.ByteString.Char8 as BC import Data.List (find)-import Data.X509.ExtensionRaw+import Data.Maybe (isNothing)+import Data.Proxy import Data.X509.DistinguishedName-import Control.Applicative-import Control.Monad+import Data.X509.ExtensionRaw+import Data.X509.Internal (asn1Container, safeCharacterToString, safeDecode) -- | key usage flag that is found in the key usage extension field.-data ExtKeyUsageFlag =- KeyUsage_digitalSignature -- (0)- | KeyUsage_nonRepudiation -- (1) recent X.509 ver have renamed this bit to contentCommitment- | KeyUsage_keyEncipherment -- (2)+data ExtKeyUsageFlag+ = KeyUsage_digitalSignature -- (0)+ | KeyUsage_nonRepudiation -- (1) recent X.509 ver have renamed this bit to contentCommitment+ | KeyUsage_keyEncipherment -- (2) | KeyUsage_dataEncipherment -- (3)- | KeyUsage_keyAgreement -- (4)- | KeyUsage_keyCertSign -- (5)- | KeyUsage_cRLSign -- (6)- | KeyUsage_encipherOnly -- (7)- | KeyUsage_decipherOnly -- (8)- deriving (Show,Eq,Ord,Enum)+ | KeyUsage_keyAgreement -- (4)+ | KeyUsage_keyCertSign -- (5)+ | KeyUsage_cRLSign -- (6)+ | KeyUsage_encipherOnly -- (7)+ | KeyUsage_decipherOnly -- (8)+ deriving (Show, Eq, Ord, Enum) {- -- RFC 5280@@ -76,35 +93,36 @@ -- e.g. raw ascii string. Add method to parse and encode with -- ByteString class Extension a where- extOID :: a -> OID+ extOID :: a -> OID extHasNestedASN1 :: Proxy a -> Bool- extEncode :: a -> [ASN1]- extDecode :: [ASN1] -> Either String a+ extEncode :: a -> [ASN1]+ extDecode :: [ASN1] -> Either String a extDecodeBs :: B.ByteString -> Either String a- extDecodeBs = (either (Left . show) Right . decodeASN1' BER) >=> extDecode+ extDecodeBs = (safeDecode . decodeASN1' BER) >=> extDecode extEncodeBs :: a -> B.ByteString extEncodeBs = encodeASN1' DER . extEncode - -- | Get a specific extension from a lists of raw extensions extensionGet :: Extension a => Extensions -> Maybe a-extensionGet (Extensions Nothing) = Nothing+extensionGet (Extensions Nothing) = Nothing extensionGet (Extensions (Just l)) = findExt l- where findExt [] = Nothing- findExt (x:xs) = case extensionDecode x of- Just (Right e) -> Just e- _ -> findExt xs+ where+ findExt [] = Nothing+ findExt (x : xs) = case extensionDecode x of+ Just (Right e) -> Just e+ _ -> findExt xs -- | Get a specific extension from a lists of raw extensions extensionGetE :: Extension a => Extensions -> Maybe (Either String a)-extensionGetE (Extensions Nothing) = Nothing+extensionGetE (Extensions Nothing) = Nothing extensionGetE (Extensions (Just l)) = findExt l- where findExt [] = Nothing- findExt (x:xs) = case extensionDecode x of- Just r -> Just r- _ -> findExt xs+ where+ findExt [] = Nothing+ findExt (x : xs) = case extensionDecode x of+ Just r -> Just r+ _ -> findExt xs -- | Try to decode an ExtensionRaw. --@@ -112,145 +130,199 @@ -- * Nothing, the OID doesn't match -- * Just Left, the OID matched, but the extension couldn't be decoded -- * Just Right, the OID matched, and the extension has been succesfully decoded-extensionDecode :: forall a . Extension a => ExtensionRaw -> Maybe (Either String a)+extensionDecode+ :: forall a. Extension a => ExtensionRaw -> Maybe (Either String a) extensionDecode er@(ExtensionRaw oid _ content)- | extOID (undefined :: a) /= oid = Nothing+ | extOID (undefined :: a) /= oid = Nothing | extHasNestedASN1 (Proxy :: Proxy a) = Just (tryExtRawASN1 er >>= extDecode)- | otherwise = Just (extDecodeBs content)+ | otherwise = Just (extDecodeBs content) -- | Encode an Extension to extensionRaw-extensionEncode :: forall a . Extension a => Bool -> a -> ExtensionRaw+extensionEncode :: forall a. Extension a => Bool -> a -> ExtensionRaw extensionEncode critical ext- | extHasNestedASN1 (Proxy :: Proxy a) = ExtensionRaw (extOID ext) critical (encodeASN1' DER $ extEncode ext)- | otherwise = ExtensionRaw (extOID ext) critical (extEncodeBs ext)+ | extHasNestedASN1 (Proxy :: Proxy a) =+ ExtensionRaw (extOID ext) critical (encodeASN1' DER $ extEncode ext)+ | otherwise =+ ExtensionRaw (extOID ext) critical (extEncodeBs ext) -- | Basic Constraints data ExtBasicConstraints = ExtBasicConstraints Bool (Maybe Integer)- deriving (Show,Eq)+ deriving (Show, Eq) instance Extension ExtBasicConstraints where- extOID = const [2,5,29,19]+ extOID = const [2, 5, 29, 19] extHasNestedASN1 = const True- extEncode (ExtBasicConstraints b Nothing) = [Start Sequence,Boolean b,End Sequence]- extEncode (ExtBasicConstraints b (Just i)) = [Start Sequence,Boolean b,IntVal i,End Sequence]+ extEncode (ExtBasicConstraints b Nothing) = [Start Sequence, Boolean b, End Sequence]+ extEncode (ExtBasicConstraints b (Just i)) = [Start Sequence, Boolean b, IntVal i, End Sequence] - extDecode [Start Sequence,Boolean b,IntVal v,End Sequence]- | v >= 0 = Right (ExtBasicConstraints b (Just v))+ extDecode [Start Sequence, Boolean b, IntVal v, End Sequence]+ | v >= 0 = Right (ExtBasicConstraints b (Just v)) | otherwise = Left "invalid pathlen"- extDecode [Start Sequence,Boolean b,End Sequence] = Right (ExtBasicConstraints b Nothing)- extDecode [Start Sequence,End Sequence] = Right (ExtBasicConstraints False Nothing)+ extDecode [Start Sequence, Boolean b, End Sequence] = Right (ExtBasicConstraints b Nothing)+ extDecode [Start Sequence, End Sequence] = Right (ExtBasicConstraints False Nothing)+ -- cA is omitted when FALSE (DER)+ extDecode [Start Sequence, IntVal v, End Sequence]+ | v >= 0 = Right (ExtBasicConstraints False (Just v))+ | otherwise = Left "invalid pathlen" extDecode _ = Left "unknown sequence" -- | Describe key usage data ExtKeyUsage = ExtKeyUsage [ExtKeyUsageFlag]- deriving (Show,Eq)+ deriving (Show, Eq) instance Extension ExtKeyUsage where- extOID = const [2,5,29,15]+ extOID = const [2, 5, 29, 15] extHasNestedASN1 = const True extEncode (ExtKeyUsage flags) = [BitString $ flagsToBits flags]- extDecode [BitString bits] = Right $ ExtKeyUsage $ bitsToFlags bits+ extDecode [BitString bits] =+ Right $ ExtKeyUsage $ bitsToFlags KeyUsage_decipherOnly bits extDecode _ = Left "unknown sequence" -- | Key usage purposes for the ExtendedKeyUsage extension-data ExtKeyUsagePurpose =- KeyUsagePurpose_ServerAuth+data ExtKeyUsagePurpose+ = KeyUsagePurpose_ServerAuth | KeyUsagePurpose_ClientAuth | KeyUsagePurpose_CodeSigning | KeyUsagePurpose_EmailProtection | KeyUsagePurpose_TimeStamping | KeyUsagePurpose_OCSPSigning | KeyUsagePurpose_Unknown OID- deriving (Show,Eq,Ord)+ deriving (Show, Eq, Ord) extKeyUsagePurposedOID :: [(OID, ExtKeyUsagePurpose)] extKeyUsagePurposedOID =- [(keyUsagePurposePrefix 1, KeyUsagePurpose_ServerAuth)- ,(keyUsagePurposePrefix 2, KeyUsagePurpose_ClientAuth)- ,(keyUsagePurposePrefix 3, KeyUsagePurpose_CodeSigning)- ,(keyUsagePurposePrefix 4, KeyUsagePurpose_EmailProtection)- ,(keyUsagePurposePrefix 8, KeyUsagePurpose_TimeStamping)- ,(keyUsagePurposePrefix 9, KeyUsagePurpose_OCSPSigning)]- where keyUsagePurposePrefix r = [1,3,6,1,5,5,7,3,r]+ [ (keyUsagePurposePrefix 1, KeyUsagePurpose_ServerAuth)+ , (keyUsagePurposePrefix 2, KeyUsagePurpose_ClientAuth)+ , (keyUsagePurposePrefix 3, KeyUsagePurpose_CodeSigning)+ , (keyUsagePurposePrefix 4, KeyUsagePurpose_EmailProtection)+ , (keyUsagePurposePrefix 8, KeyUsagePurpose_TimeStamping)+ , (keyUsagePurposePrefix 9, KeyUsagePurpose_OCSPSigning)+ ]+ where+ keyUsagePurposePrefix r = [1, 3, 6, 1, 5, 5, 7, 3, r] -- | Extended key usage extension data ExtExtendedKeyUsage = ExtExtendedKeyUsage [ExtKeyUsagePurpose]- deriving (Show,Eq)+ deriving (Show, Eq) instance Extension ExtExtendedKeyUsage where- extOID = const [2,5,29,37]+ extOID = const [2, 5, 29, 37] extHasNestedASN1 = const True extEncode (ExtExtendedKeyUsage purposes) = [Start Sequence] ++ map (OID . lookupRev) purposes ++ [End Sequence]- where lookupRev (KeyUsagePurpose_Unknown oid) = oid- lookupRev kup = maybe (error "unknown key usage purpose") fst $ find ((==) kup . snd) extKeyUsagePurposedOID- extDecode l = ExtExtendedKeyUsage `fmap` (flip runParseASN1 l $ onNextContainer Sequence $ getMany $ do- n <- getNext- case n of- OID o -> return $ maybe (KeyUsagePurpose_Unknown o) id $ lookup o extKeyUsagePurposedOID- _ -> error "invalid content in extended key usage")+ where+ lookupRev (KeyUsagePurpose_Unknown oid) = oid+ lookupRev kup =+ maybe (error "unknown key usage purpose") fst $+ find ((==) kup . snd) extKeyUsagePurposedOID+ extDecode l =+ ExtExtendedKeyUsage+ `fmap` ( flip runParseASN1 l $ onNextContainer Sequence $ getMany $ do+ n <- getNext+ case n of+ OID o ->+ return $ maybe (KeyUsagePurpose_Unknown o) id $ lookup o extKeyUsagePurposedOID+ _ -> throwParseError "invalid content in extended key usage"+ ) -- | Provide a way to identify a public key by a short hash. data ExtSubjectKeyId = ExtSubjectKeyId B.ByteString- deriving (Show,Eq)+ deriving (Show, Eq) instance Extension ExtSubjectKeyId where- extOID = const [2,5,29,14]+ extOID = const [2, 5, 29, 14] extHasNestedASN1 = const True extEncode (ExtSubjectKeyId o) = [OctetString o] 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--- directoryName--- ediPartyName--- registeredID----data AltName =- AltNameRFC822 String+-- | GeneralName (RFC 5280 4.2.1.6).+data AltName+ = AltNameRFC822 String | AltNameDNS String+ | AltNameDN DistinguishedName | AltNameURI String- | AltNameIP B.ByteString+ | AltNameIP B.ByteString | AltNameXMPP String | AltNameDNSSRV String- deriving (Show,Eq,Ord)+ | -- | 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 -- used for matching host name. data ExtSubjectAltName = ExtSubjectAltName [AltName]- deriving (Show,Eq,Ord)+ deriving (Show, Eq, Ord) instance Extension ExtSubjectAltName where- extOID = const [2,5,29,17]+ extOID = const [2, 5, 29, 17] extHasNestedASN1 = const True 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- deriving (Show,Eq)+-- | 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]+ extOID _ = [2, 5, 29, 35] extHasNestedASN1 = const True- extEncode (ExtAuthorityKeyId keyid) =- [Start Sequence,Other Context 0 keyid,End Sequence]- extDecode [Start Sequence,Other Context 0 keyid,End Sequence] =- Right $ ExtAuthorityKeyId keyid- 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]- deriving (Show,Eq)+ deriving (Show, Eq) -- | Reason flag for the CRL-data ReasonFlag =- Reason_Unused+data ReasonFlag+ = Reason_Unused | Reason_KeyCompromise | Reason_CACompromise | Reason_AffiliationChanged@@ -259,92 +331,412 @@ | Reason_CertificateHold | Reason_PrivilegeWithdrawn | Reason_AACompromise- deriving (Show,Eq,Ord,Enum)+ deriving (Show, Eq, Ord, Enum) --- | Distribution point as either some GeneralNames or a DN-data DistributionPoint =- DistributionPointFullName [AltName]- | DistributionNameRelative DistinguishedName- deriving (Show,Eq)+-- | 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]+ | DistributionPointRelativeName RelativeDistinguishedName+ deriving (Show, Eq)+ instance Extension ExtCrlDistributionPoints where- extOID _ = [2,5,29,31]+ extOID _ = [2, 5, 29, 31] extHasNestedASN1 = const True- extEncode = error "extEncode ExtCrlDistributionPoints unimplemented"- extDecode = error "extDecode ExtCrlDistributionPoints unimplemented"- --extEncode (ExtCrlDistributionPoints )+ extEncode (ExtCrlDistributionPoints dps) =+ asn1Container Sequence $ concatMap encodeDP dps+ where+ 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 dps+ parseDP = onNextContainer Sequence $ do+ name <- onNextContainerMaybe (Container Context 0) parseName+ 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) (getMany getAddr)+ case full of+ Just names -> return $ DistributionPointFullName names+ Nothing ->+ maybe (throwParseError "DistributionPoint: unknown name") return+ =<< onNextContainerMaybe+ (Container Context 1)+ (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 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 parseGeneralNames :: ParseASN1 [AltName]-parseGeneralNames = onNextContainer Sequence $ getMany getAddr+parseGeneralNames = onNextContainer Sequence $ do+ names <- getMany getAddr+ forM_ names $ \name -> case name of+ AltNameIP ip+ | B.length ip /= 4 && B.length ip /= 16 ->+ throwParseError "GeneralNames: invalid iPAddress length"+ _ -> return ()+ return names++getAddr :: ParseASN1 AltName+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 $ AltNameDN dn+ Nothing -> getConstructedOrSimpleAddr where- getAddr = do- m <- onNextContainerMaybe (Container Context 0) getComposedAddr- case m of- Nothing -> getSimpleAddr- Just r -> return r- getComposedAddr = do- n <- getNext- case n of- OID [1,3,6,1,5,5,7,8,5] -> do -- xmpp addr- c <- getNextContainerMaybe (Container Context 0)- case c of- Just [ASN1String cs] ->- case asn1CharacterToString cs of- Nothing -> throwParseError ("GeneralNames: invalid string for XMPP Addr")- 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 -- DNSSRV addr- c <- getNextContainerMaybe (Container Context 0)- case c of- Just [ASN1String cs] ->- case asn1CharacterToString cs of- Nothing -> throwParseError ("GeneralNames: invalid string for DNSSrv Addr")- Just s -> return $ AltNameDNSSRV s- _ -> throwParseError ("GeneralNames: expecting string for DNSSRV Addr got: " ++ show c)- OID unknown -> throwParseError ("GeneralNames: unknown OID " ++ show unknown)- _ -> throwParseError ("GeneralNames: expecting OID but got " ++ show n)+ getComposedAddr = do+ n <- getNext+ case n of+ OID [1, 3, 6, 1, 5, 5, 7, 8, 5] -> do+ -- xmpp addr+ c <- getNextContainerMaybe (Container Context 0)+ case c of+ Just [ASN1String cs] ->+ case safeCharacterToString cs of+ Nothing -> throwParseError ("GeneralNames: invalid string for XMPP Addr")+ 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+ -- DNSSRV addr+ c <- getNextContainerMaybe (Container Context 0)+ case c of+ Just [ASN1String cs] ->+ case safeCharacterToString cs of+ Nothing -> throwParseError ("GeneralNames: invalid string for DNSSrv Addr")+ Just s -> return $ AltNameDNSSRV s+ _ ->+ throwParseError+ ("GeneralNames: expecting string for DNSSRV Addr got: " ++ show c)+ 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 $ AltNameRFC822 $ BC.unpack b- (Other Context 2 b) -> return $ AltNameDNS $ BC.unpack b- (Other Context 6 b) -> return $ AltNameURI $ BC.unpack b- (Other Context 7 b) -> return $ AltNameIP b- _ -> throwParseError ("GeneralNames: not coping with unknown stream " ++ show n)+ getSimpleAddr = do+ n <- getNext+ case n of+ (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 $ AltNameDN dn+ Left e2 -> throwParseError e2+ (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)+ getConstructedOrSimpleAddr = do+ x400 <- getNextContainerMaybe (Container Context 3)+ 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]- ++ concatMap encodeAltName names- ++ [End Sequence]- where encodeAltName (AltNameRFC822 n) = [Other Context 1 $ BC.pack n]- encodeAltName (AltNameDNS n) = [Other Context 2 $ BC.pack n]- encodeAltName (AltNameURI n) = [Other Context 6 $ BC.pack n]- encodeAltName (AltNameIP n) = [Other Context 7 $ n]- encodeAltName (AltNameXMPP n) = [Start (Container Context 0),OID[1,3,6,1,5,5,7,8,5]- ,Start (Container Context 0), ASN1String $ asn1CharacterString UTF8 n, End (Container Context 0)- ,End (Container Context 0)]- encodeAltName (AltNameDNSSRV n) = [Start (Container Context 0),OID[1,3,6,1,5,5,7,8,5]- ,Start (Container Context 0), ASN1String $ asn1CharacterString UTF8 n, End (Container Context 0)- ,End (Container Context 0)]+ ++ concatMap encodeAltName names+ ++ [End Sequence] -bitsToFlags :: Enum a => BitArray -> [a]-bitsToFlags bits = concat $ flip map [0..(bitArrayLength bits-1)] $ \i -> do- let isSet = bitArrayGetBit bits i- if isSet then [toEnum $ fromIntegral i] else []+encodeAltName :: AltName -> [ASN1]+encodeAltName (AltNameRFC822 n) = [Other Context 1 $ BC.pack n]+encodeAltName (AltNameDNS n) = [Other Context 2 $ BC.pack n]+encodeAltName (AltNameDN dn) =+ [Start (Container Context 4)] ++ toASN1 dn [End (Container Context 4)]+encodeAltName (AltNameURI n) = [Other Context 6 $ BC.pack n]+encodeAltName (AltNameIP n) = [Other Context 7 $ n]+encodeAltName (AltNameXMPP n) =+ [ Start (Container Context 0)+ , OID [1, 3, 6, 1, 5, 5, 7, 8, 5]+ , Start (Container Context 0)+ , ASN1String $ asn1CharacterString UTF8 n+ , End (Container Context 0)+ , End (Container Context 0)+ ]+encodeAltName (AltNameDNSSRV n) =+ [ Start (Container Context 0)+ , OID [1, 3, 6, 1, 5, 5, 7, 8, 7]+ , Start (Container Context 0)+ , ASN1String $ asn1CharacterString UTF8 n+ , 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.+bitsToFlags :: Enum a => a -> BitArray -> [a]+bitsToFlags lastFlag bits =+ [toEnum (fromIntegral i) | len > 0, i <- [0 .. len - 1], bitArrayGetBit bits i]+ where+ dataLen = 8 * fromIntegral (B.length (bitArrayGetData bits))+ len = minimum [bitArrayLength bits, dataLen, fromIntegral (fromEnum lastFlag) + 1]++-- | DER: trailing zero bits are removed. flagsToBits :: Enum a => [a] -> BitArray-flagsToBits flags = foldl bitArraySetBit bitArrayEmpty $ map (fromIntegral . fromEnum) flags- where bitArrayEmpty = toBitArray (B.pack [0,0]) 7+flagsToBits flags = toBitArray (B.pack bytes) (8 * nbytes - len)+ where+ ixs = map fromEnum flags+ len = if null ixs then 0 else maximum ixs + 1+ nbytes = (len + 7) `div` 8+ bytes =+ [ foldl (.|.) 0 [bit (7 - i `mod` 8) | i <- ixs, i `div` 8 == n]+ | n <- [0 .. nbytes - 1]+ ] data ExtNetscapeComment = ExtNetscapeComment B.ByteString- deriving (Show,Eq)+ deriving (Show, Eq) instance Extension ExtNetscapeComment where- extOID _ = [2,16,840,1,113730,1,13]+ extOID _ = [2, 16, 840, 1, 113730, 1, 13] extHasNestedASN1 = const False extEncode = error "Extension: Netscape Comment do not contain nested ASN1" extDecode = error "Extension: Netscape Comment do not contain nested ASN1" extEncodeBs (ExtNetscapeComment b) = b extDecodeBs = Right . ExtNetscapeComment++--------------------------------------------------------------------------------+-- RFC5280+--+-- NameConstraints ::= SEQUENCE {+-- permittedSubtrees [0] GeneralSubtrees OPTIONAL,+-- excludedSubtrees [1] GeneralSubtrees OPTIONAL+-- }+--+-- GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree+--+-- GeneralSubtree ::= SEQUENCE {+-- base GeneralName,+-- minimum [0] BaseDistance DEFAULT 0,+-- maximum [1] BaseDistance OPTIONAL+-- }+--------------------------------------------------------------------------------++data GeneralSubtree = GeneralSubtree AltName Integer (Maybe Integer)+ deriving (Show, Eq)++data ExtNameConstraints = ExtNameConstraints [GeneralSubtree] [GeneralSubtree]+ deriving (Show, Eq)++instance Extension ExtNameConstraints where+ extOID _ = [2, 5, 29, 30]+ extHasNestedASN1 _ = True+ extEncode = encodeNameConstraints+ extDecode = decodeNameConstraints++--------------------------------------------------------------------------------+-- Encoding+--------------------------------------------------------------------------------++encodeNameConstraints :: ExtNameConstraints -> [ASN1]+encodeNameConstraints (ExtNameConstraints permitted excluded) =+ [Start Sequence]+ ++ put 0 permitted+ ++ put 1 excluded+ ++ [End Sequence]+ where+ put _ [] = []+ -- IMPLICIT tagging: the tag replaces the SEQUENCE OF+ put n xs =+ [Start (Container Context n)]+ ++ concatMap encodeGeneralSubtree xs+ ++ [End (Container Context n)]++encodeGeneralSubtree :: GeneralSubtree -> [ASN1]+encodeGeneralSubtree (GeneralSubtree base minimum' maximum') =+ [Start Sequence]+ ++ encodeAltName base+ ++ (if minimum' /= 0 then [Other Context 0 (intContent minimum')] else [])+ ++ maybe [] (\m -> [Other Context 1 (intContent m)]) maximum'+ ++ [End Sequence]++--------------------------------------------------------------------------------+-- Decoding+--------------------------------------------------------------------------------++decodeNameConstraints :: [ASN1] -> Either String ExtNameConstraints+decodeNameConstraints+ (Start Sequence : xs) =+ go xs [] []+ where+ go (End Sequence : _) permitted excluded =+ Right $ ExtNameConstraints permitted excluded+ go (Start (Container Context 0) : rest) _ excluded = do+ (subs, rest') <- decodeSubtrees rest+ go rest' subs excluded+ go (Start (Container Context 1) : rest) permitted _ = do+ (subs, rest') <- decodeSubtrees rest+ go rest' permitted subs+ go _ _ _ = Left "Invalid NameConstraints"+ decodeSubtrees :: [ASN1] -> Either String ([GeneralSubtree], [ASN1])+ decodeSubtrees ys = loop ys []+ where+ loop (End (Container Context _) : _) [] =+ Left "NameConstraints: empty GeneralSubtrees"+ loop (End (Container Context _) : rest) acc =+ Right (reverse acc, rest)+ loop zs acc = do+ (s, zs') <- decodeGeneralSubtree zs+ loop zs' (s : acc)+decodeNameConstraints _ =+ Left "NameConstraints: expected SEQUENCE"++decodeGeneralSubtree+ :: [ASN1]+ -> Either String (GeneralSubtree, [ASN1])+decodeGeneralSubtree (Start Sequence : xs) = do+ (base, rest1) <- runParseASN1State getAddr xs+ -- an iPAddress constraint is an address followed by a mask+ case base of+ AltNameIP ip+ | B.length ip /= 8 && B.length ip /= 32 ->+ Left "GeneralSubtree: invalid iPAddress length"+ _ -> Right ()++ (minimum', rest2) <- case rest1 of+ (Other Context 0 bs : rs) -> (\n -> (n, rs)) <$> implicitInt bs+ _ -> Right (0, rest1)+ (maximum', rest3) <- case rest2 of+ (Other Context 1 bs : rs) -> (\n -> (Just n, rs)) <$> implicitInt bs+ _ -> Right (Nothing, rest2)++ case rest3 of+ (End Sequence : rs) ->+ Right (GeneralSubtree base minimum' maximum', rs)+ _ ->+ Left "GeneralSubtree: missing end sequence"+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 "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++recognizedOIDs :: [OID]+recognizedOIDs =+ [ [2, 5, 29, 19] -- ExtBasicConstraints+ , [2, 5, 29, 15] -- ExtKeyUsage+ , [2, 5, 29, 37] -- ExtExtendedKeyUsage+ , [2, 5, 29, 14] -- ExtSubjectKeyId+ , [2, 5, 29, 17] -- ExtSubjectAltName+ , [2, 5, 29, 35] -- ExtAuthorityKeyId+ , [2, 5, 29, 31] -- ExtCrlDistributionPoints+ , [2, 5, 29, 30] -- ExtNameConstraints+ , [2, 16, 840, 1, 113730, 1, 13] -- ExtNetscapeComment+ ]
Data/X509/ExtensionRaw.hs view
@@ -6,33 +6,41 @@ -- Portability : unknown -- -- extension marshalling----module Data.X509.ExtensionRaw- ( ExtensionRaw(..)- , tryExtRawASN1- , extRawASN1- , Extensions(..)- ) where+module Data.X509.ExtensionRaw (+ ExtensionRaw (..),+ tryExtRawASN1,+ extRawASN1,+ Extensions (..),+) where -import Control.Applicative-import Data.ASN1.Types-import Data.ASN1.Encoding import Data.ASN1.BinaryEncoding-import Data.X509.Internal+import Data.ASN1.Encoding+import Data.ASN1.Types import qualified Data.ByteString as B+import Data.List (nub)+import Data.X509.Internal -- | An undecoded extension data ExtensionRaw = ExtensionRaw- { extRawOID :: OID -- ^ OID of this extension- , extRawCritical :: Bool -- ^ if this extension is critical- , extRawContent :: B.ByteString -- ^ undecoded content- } deriving (Show,Eq)+ { extRawOID :: OID+ -- ^ OID of this extension+ , extRawCritical :: Bool+ -- ^ if this extension is critical+ , extRawContent :: B.ByteString+ -- ^ undecoded content+ }+ deriving (Show, Eq) tryExtRawASN1 :: ExtensionRaw -> Either String [ASN1] tryExtRawASN1 (ExtensionRaw oid _ content) =- case decodeASN1' BER content of- Left err -> Left $ "fromASN1: X509.ExtensionRaw: OID=" ++ show oid ++ ": cannot decode data: " ++ show err- Right r -> Right r+ case safeDecode (decodeASN1' BER content) of+ Left err ->+ Left $+ "fromASN1: X509.ExtensionRaw: OID="+ ++ show oid+ ++ ": cannot decode data: "+ ++ err+ Right r -> Right r extRawASN1 :: ExtensionRaw -> [ASN1] extRawASN1 extRaw = either error id $ tryExtRawASN1 extRaw@@ -40,25 +48,37 @@ -- | a Set of 'ExtensionRaw' newtype Extensions = Extensions (Maybe [ExtensionRaw])- deriving (Show,Eq)+ deriving (Show, Eq) instance ASN1Object Extensions where toASN1 (Extensions Nothing) = \xs -> xs toASN1 (Extensions (Just exts)) = \xs -> asn1Container Sequence (concatMap encodeExt exts) ++ xs fromASN1 s = runParseASN1State (Extensions <$> parseExtensions) s- where parseExtensions = onNextContainerMaybe Sequence (getMany getObject)+ where+ -- RFC 5280: at most one instance of a particular extension+ parseExtensions = do+ mexts <- onNextContainerMaybe Sequence (getMany getObject)+ case mexts of+ Just exts+ | let oids = map extRawOID exts+ , length (nub oids) /= length oids ->+ throwParseError "fromASN1: X509.Extensions: duplicate extension"+ _ -> return mexts instance ASN1Object ExtensionRaw where toASN1 extraw = \xs -> encodeExt extraw ++ xs- fromASN1 (Start Sequence:OID oid:xs) =+ fromASN1 (Start Sequence : OID oid : xs) = case xs of- Boolean b:OctetString obj:End Sequence:xs2 -> Right (ExtensionRaw oid b obj, xs2)- OctetString obj:End Sequence:xs2 -> Right (ExtensionRaw oid False obj, xs2)- _ -> Left ("fromASN1: X509.ExtensionRaw: unknown format:" ++ show xs)- fromASN1 l =+ Boolean b : OctetString obj : End Sequence : xs2 -> Right (ExtensionRaw oid b obj, xs2)+ OctetString obj : End Sequence : xs2 -> Right (ExtensionRaw oid False obj, xs2)+ _ ->+ Left ("fromASN1: X509.ExtensionRaw: unknown format:" ++ show xs)+ fromASN1 l = Left ("fromASN1: X509.ExtensionRaw: unknown format:" ++ show l) encodeExt :: ExtensionRaw -> [ASN1] encodeExt (ExtensionRaw oid critical content) =- asn1Container Sequence ([OID oid] ++ (if critical then [Boolean True] else []) ++ [OctetString content])+ asn1Container+ Sequence+ ([OID oid] ++ (if critical then [Boolean True] else []) ++ [OctetString content])
Data/X509/Internal.hs view
@@ -1,27 +1,91 @@+{-# LANGUAGE ScopedTypeVariables #-}+ -- | -- Module : Data.X509.Internal -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown----module Data.X509.Internal- ( module Data.ASN1.Parse- , asn1Container- , OID+module Data.X509.Internal (+ module Data.ASN1.Parse,+ asn1Container,+ OID,+ -- * error handling- , ErrT- , runErrT- ) where+ ErrT,+ runErrT,+ safeDecode,+ safeCharacterToString, -import Data.ASN1.Types-import Data.ASN1.Parse+ -- * time+ asn1TimeToUTC,+ encodeASN1Time,+) where++import Control.Exception (+ SomeAsyncException,+ SomeException,+ evaluate,+ fromException,+ throwIO,+ try,+ ) import Control.Monad.Trans.Except+import Data.ASN1.Parse+import Data.ASN1.Types+import Data.Hourglass+import qualified Data.List as L+import System.IO.Unsafe (unsafeDupablePerformIO) runErrT :: ExceptT e m a -> m (Either e a) runErrT = runExceptT type ErrT = ExceptT +-- | A decoded time converted to UTC with its zone offset.+asn1TimeToUTC :: DateTime -> Maybe TimezoneOffset -> DateTime+asn1TimeToUTC t (Just (TimezoneOffset m))+ | m /= 0 = timeAdd t (Seconds (fromIntegral (negate m) * 60))+asn1TimeToUTC t _ = t++-- | RFC 5280 4.1.2.5: UTCTime through 2049 from 1950, GeneralizedTime+-- otherwise.+encodeASN1Time :: DateTime -> ASN1+encodeASN1Time t = ASN1Time ty t (Just (TimezoneOffset 0))+ where+ y = dateYear (dtDate t)+ ty+ | y >= 1950 && y < 2050 = TimeUTC+ | otherwise = TimeGeneralized+ -- | create a container around the stream of ASN1 asn1Container :: ASN1ConstructionType -> [ASN1] -> [ASN1] asn1Container ty l = [Start ty] ++ l ++ [End ty]++-- | Force a decoded ASN.1 stream so that errors thrown lazily from inside+-- the list by the decoder are turned into 'Left'.+safeDecode :: Show e => Either e [a] -> Either String [a]+safeDecode r = case tryPure forceE r of+ Left err -> Left err+ Right (Left e) -> Left (show e)+ Right (Right xs) -> Right xs+ where+ forceE (Left e) = length (show e) `seq` ()+ forceE (Right xs) = L.foldl' (flip seq) () xs++-- | Like 'asn1CharacterToString' but 'Nothing' on invalid encoding.+safeCharacterToString :: ASN1CharacterString -> Maybe String+safeCharacterToString cs =+ asn1CharacterToString cs >>= either (const Nothing) Just . tryPure force+ where+ force = L.foldl' (flip seq) ()++-- | Run a forcing function and turn synchronous exceptions into 'Left'.+tryPure :: (a -> ()) -> a -> Either String a+tryPure force x = unsafeDupablePerformIO $ do+ res <- try $ evaluate $ force x+ case res of+ Right () -> return $ Right x+ Left (e :: SomeException)+ | Just (_ :: SomeAsyncException) <- fromException e -> throwIO e+ | otherwise -> return $ Left (show e)+{-# NOINLINE tryPure #-}
Data/X509/OID.hs view
@@ -4,20 +4,18 @@ -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown----module Data.X509.OID- ( OIDTable- , lookupByOID- , lookupOID- , curvesOIDTable- ) where+module Data.X509.OID (+ OIDTable,+ lookupByOID,+ lookupOID,+ curvesOIDTable,+) where -import Control.Applicative import Crypto.PubKey.ECC.Types import Data.ASN1.OID import Data.List (find) -type OIDTable a = [(a,OID)]+type OIDTable a = [(a, OID)] lookupByOID :: OIDTable a -> OID -> Maybe a lookupByOID table oid = fst <$> find ((==) oid . snd) table@@ -27,37 +25,37 @@ curvesOIDTable :: OIDTable CurveName curvesOIDTable =- [ (SEC_p112r1, [1,3,132,0,6])- , (SEC_p112r2, [1,3,132,0,7])- , (SEC_p128r1, [1,3,132,0,28])- , (SEC_p128r2, [1,3,132,0,29])- , (SEC_p160k1, [1,3,132,0,9])- , (SEC_p160r1, [1,3,132,0,8])- , (SEC_p160r2, [1,3,132,0,30])- , (SEC_p192k1, [1,3,132,0,31])- , (SEC_p192r1, [1,2,840,10045,3,1,1])- , (SEC_p224k1, [1,3,132,0,32])- , (SEC_p224r1, [1,3,132,0,33])- , (SEC_p256k1, [1,3,132,0,10])- , (SEC_p256r1, [1,2,840,10045,3,1,7])- , (SEC_p384r1, [1,3,132,0,34])- , (SEC_p521r1, [1,3,132,0,35])- , (SEC_t113r1, [1,3,132,0,4])- , (SEC_t113r2, [1,3,132,0,5])- , (SEC_t131r1, [1,3,132,0,22])- , (SEC_t131r2, [1,3,132,0,23])- , (SEC_t163k1, [1,3,132,0,1])- , (SEC_t163r1, [1,3,132,0,2])- , (SEC_t163r2, [1,3,132,0,15])- , (SEC_t193r1, [1,3,132,0,24])- , (SEC_t193r2, [1,3,132,0,25])- , (SEC_t233k1, [1,3,132,0,26])- , (SEC_t233r1, [1,3,132,0,27])- , (SEC_t239k1, [1,3,132,0,3])- , (SEC_t283k1, [1,3,132,0,16])- , (SEC_t283r1, [1,3,132,0,17])- , (SEC_t409k1, [1,3,132,0,36])- , (SEC_t409r1, [1,3,132,0,37])- , (SEC_t571k1, [1,3,132,0,38])- , (SEC_t571r1, [1,3,132,0,39])+ [ (SEC_p112r1, [1, 3, 132, 0, 6])+ , (SEC_p112r2, [1, 3, 132, 0, 7])+ , (SEC_p128r1, [1, 3, 132, 0, 28])+ , (SEC_p128r2, [1, 3, 132, 0, 29])+ , (SEC_p160k1, [1, 3, 132, 0, 9])+ , (SEC_p160r1, [1, 3, 132, 0, 8])+ , (SEC_p160r2, [1, 3, 132, 0, 30])+ , (SEC_p192k1, [1, 3, 132, 0, 31])+ , (SEC_p192r1, [1, 2, 840, 10045, 3, 1, 1])+ , (SEC_p224k1, [1, 3, 132, 0, 32])+ , (SEC_p224r1, [1, 3, 132, 0, 33])+ , (SEC_p256k1, [1, 3, 132, 0, 10])+ , (SEC_p256r1, [1, 2, 840, 10045, 3, 1, 7])+ , (SEC_p384r1, [1, 3, 132, 0, 34])+ , (SEC_p521r1, [1, 3, 132, 0, 35])+ , (SEC_t113r1, [1, 3, 132, 0, 4])+ , (SEC_t113r2, [1, 3, 132, 0, 5])+ , (SEC_t131r1, [1, 3, 132, 0, 22])+ , (SEC_t131r2, [1, 3, 132, 0, 23])+ , (SEC_t163k1, [1, 3, 132, 0, 1])+ , (SEC_t163r1, [1, 3, 132, 0, 2])+ , (SEC_t163r2, [1, 3, 132, 0, 15])+ , (SEC_t193r1, [1, 3, 132, 0, 24])+ , (SEC_t193r2, [1, 3, 132, 0, 25])+ , (SEC_t233k1, [1, 3, 132, 0, 26])+ , (SEC_t233r1, [1, 3, 132, 0, 27])+ , (SEC_t239k1, [1, 3, 132, 0, 3])+ , (SEC_t283k1, [1, 3, 132, 0, 16])+ , (SEC_t283r1, [1, 3, 132, 0, 17])+ , (SEC_t409k1, [1, 3, 132, 0, 36])+ , (SEC_t409r1, [1, 3, 132, 0, 37])+ , (SEC_t571k1, [1, 3, 132, 0, 38])+ , (SEC_t571r1, [1, 3, 132, 0, 39]) ]
Data/X509/PrivateKey.hs view
@@ -1,121 +1,464 @@+{-# 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 -- Portability : unknown -- -- Private key handling in X.509 infrastructure----module Data.X509.PrivateKey- ( PrivKey(..)- , PrivKeyEC(..)- , privkeyToAlg- ) where+module Data.X509.PrivateKey (+ PrivKey (..),+ PrivKeyEC (..),+ PrivKeyMLDSA,+ 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 -import Control.Applicative ((<$>), pure) import Data.Maybe (fromMaybe)-import Data.Word (Word)+import Data.Proxy (Proxy (..)) -import Data.ByteArray (ByteArrayAccess, convert)+import Data.ByteArray (ByteArrayAccess, ScrubbedBytes, convert) import qualified Data.ByteString as B -import Data.ASN1.Types-import Data.ASN1.Encoding import Data.ASN1.BinaryEncoding import Data.ASN1.BitArray+import Data.ASN1.Encoding import Data.ASN1.Stream (getConstructedEnd)+import Data.ASN1.Types import Data.X509.AlgorithmIdentifier-import Data.X509.PublicKey (SerializedPoint(..))-import Data.X509.OID (lookupByOID, lookupOID, curvesOIDTable)+import Data.X509.Internal (safeDecode)+import Data.X509.OID (curvesOIDTable, lookupByOID, lookupOID)+import Data.X509.PublicKey (SerializedPoint (..)) -import Crypto.Error (CryptoFailable(..))-import Crypto.Number.Serialize (i2osp, os2ip)-import qualified Crypto.PubKey.RSA as RSA+import Crypto.Debug (DebugShow (..), debugShowBytes)+import Crypto.Error (CryptoFailable (..))+import Crypto.Number.Basic (numBytes)+import Crypto.Number.Serialize (i2osp, i2ospOf_, os2ip)+import qualified Crypto.PubKey.Curve25519 as X25519+import qualified Crypto.PubKey.Curve448 as X448 import qualified Crypto.PubKey.DSA as DSA import qualified Crypto.PubKey.ECC.Types as ECC-import qualified Crypto.PubKey.Curve25519 as X25519-import qualified Crypto.PubKey.Curve448 as X448-import qualified Crypto.PubKey.Ed25519 as Ed25519-import qualified Crypto.PubKey.Ed448 as Ed448+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 -- -- TODO: missing support for binary curve.-data PrivKeyEC =- PrivKeyEC_Prime- { privkeyEC_priv :: Integer- , privkeyEC_a :: Integer- , privkeyEC_b :: Integer- , privkeyEC_prime :: Integer+data PrivKeyEC+ = PrivKeyEC_Prime+ { privkeyEC_priv :: Integer+ , privkeyEC_a :: Integer+ , privkeyEC_b :: Integer+ , privkeyEC_prime :: Integer , privkeyEC_generator :: SerializedPoint- , privkeyEC_order :: Integer- , privkeyEC_cofactor :: Integer- , privkeyEC_seed :: Integer+ , privkeyEC_order :: Integer+ , privkeyEC_cofactor :: Integer+ , privkeyEC_seed :: Integer } | PrivKeyEC_Named- { privkeyEC_name :: ECC.CurveName- , privkeyEC_priv :: Integer+ { privkeyEC_name :: ECC.CurveName+ , privkeyEC_priv :: Integer }- deriving (Show,Eq)+ deriving (Eq) +-- | The curve is shown; @privkeyEC_priv@ is not. Use+-- 'Crypto.Debug.debugShow' to see it.+instance Show PrivKeyEC where+ showsPrec = showsPrivKeyEC (showString "<secret>")++instance DebugShow PrivKeyEC where+ debugShow k = showsPrivKeyEC (shows $ privkeyEC_priv k) 0 k ""++-- | What the two instances above share, so that a field added to+-- 'PrivKeyEC' cannot reach one of them and not the other. The first+-- argument renders @privkeyEC_priv@; everything else is what @deriving+-- Show@ used to write.+showsPrivKeyEC :: ShowS -> Int -> PrivKeyEC -> ShowS+showsPrivKeyEC priv d (PrivKeyEC_Prime _ a b p g o c s) =+ showParen (d > 10) $+ showString "PrivKeyEC_Prime {privkeyEC_priv = "+ . priv+ . showString ", privkeyEC_a = "+ . shows a+ . showString ", privkeyEC_b = "+ . shows b+ . showString ", privkeyEC_prime = "+ . shows p+ . showString ", privkeyEC_generator = "+ . shows g+ . showString ", privkeyEC_order = "+ . shows o+ . showString ", privkeyEC_cofactor = "+ . shows c+ . showString ", privkeyEC_seed = "+ . shows s+ . showChar '}'+showsPrivKeyEC priv d (PrivKeyEC_Named n _) =+ showParen (d > 10) $+ showString "PrivKeyEC_Named {privkeyEC_name = "+ . shows n+ . showString ", privkeyEC_priv = "+ . priv+ . showChar '}'++-- | 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.+ MLKeySeed+ | -- | The expanded key alone, @expandedKey@.+ MLKeyExpanded+ | -- | Both together, @both@.+ 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+-- expanded key, or as both, and which of the three it was is part of the+-- key here. A key read from a file is therefore written back out as the+-- same thing it came in as, rather than as whichever form this module+-- happens to prefer.+--+-- The expanded key is there whatever the form: a seed is expanded as it is+-- read, so 'privkeyMLDSA_key' always answers. The seed is not, since a+-- key written as @expandedKey@ does not carry one; 'privkeyMLDSA_seed' is+-- a 'Maybe' for that reason, and a key whose seed was never on the wire+-- cannot be given one back -- @crypton@'s+-- @Crypto.PubKey.MLDSA.generateKeyPairAndSeed@ is where a seed that is to+-- be kept has to be caught.+--+-- The constructors are not exported: a seed and an expanded key that do+-- not belong together would be a key that signs with one and claims the+-- other, so the only ways in are 'privkeyMLDSAFromSeed', which expands the+-- seed itself, and 'privkeyMLDSAFromKey', which has no seed to disagree+-- with.+--+-- Two keys are equal when they hold the same thing /in the same form/: the+-- same key as a seed and as an expanded key are two different files, and+-- the encoding round trip says so.+data PrivKeyMLDSA p+ = PrivKeyMLDSA_Seed ScrubbedBytes (MLDSA.SigningKey p)+ | PrivKeyMLDSA_Expanded (MLDSA.SigningKey p)+ | PrivKeyMLDSA_Both ScrubbedBytes (MLDSA.SigningKey p)+ deriving (Eq)++-- | What the two instances below share, so that a form added to+-- 'PrivKeyMLDSA' cannot reach one of them and not the other. The+-- arguments render the seed and the key.+showsPrivKeyMLDSA+ :: (ScrubbedBytes -> String)+ -> (MLDSA.SigningKey p -> String)+ -> PrivKeyMLDSA p+ -> String+showsPrivKeyMLDSA seed key k = case k of+ PrivKeyMLDSA_Seed s sk -> con "PrivKeyMLDSA_Seed" [seed s, key sk]+ PrivKeyMLDSA_Expanded sk -> con "PrivKeyMLDSA_Expanded" [key sk]+ PrivKeyMLDSA_Both s sk -> con "PrivKeyMLDSA_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. Use+-- 'Crypto.Debug.debugShow' to see them.+instance Show (PrivKeyMLDSA p) where+ show = showsPrivKeyMLDSA (const "<secret>") show++instance DebugShow (PrivKeyMLDSA p) where+ debugShow = showsPrivKeyMLDSA (debugShowBytes "seed") debugShow++-- | 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 '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 -> 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+ MLKeySeed -> PrivKeyMLDSA_Seed seed sk+ MLKeyExpanded -> PrivKeyMLDSA_Expanded sk+ MLKeyBoth -> PrivKeyMLDSA_Both seed sk+ where+ seed = convert bs :: ScrubbedBytes++-- | Build a key from the expanded key alone, which is what a key that was+-- generated without keeping its seed has to be.+privkeyMLDSAFromKey :: MLDSA.SigningKey p -> PrivKeyMLDSA p+privkeyMLDSAFromKey = PrivKeyMLDSA_Expanded++-- | The expanded key, whatever form the key is in.+privkeyMLDSA_key :: PrivKeyMLDSA p -> MLDSA.SigningKey p+privkeyMLDSA_key (PrivKeyMLDSA_Seed _ sk) = sk+privkeyMLDSA_key (PrivKeyMLDSA_Expanded sk) = sk+privkeyMLDSA_key (PrivKeyMLDSA_Both _ sk) = sk++-- | The seed, for a key that has one.+privkeyMLDSA_seed :: PrivKeyMLDSA p -> Maybe ScrubbedBytes+privkeyMLDSA_seed (PrivKeyMLDSA_Seed s _) = Just s+privkeyMLDSA_seed (PrivKeyMLDSA_Expanded _) = Nothing+privkeyMLDSA_seed (PrivKeyMLDSA_Both s _) = Just s++-- | The form the key will be written out in.+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 =- PrivKeyRSA RSA.PrivateKey -- ^ RSA private key- | PrivKeyDSA DSA.PrivateKey -- ^ DSA private key- | PrivKeyEC PrivKeyEC -- ^ EC private key- | PrivKeyX25519 X25519.SecretKey -- ^ X25519 private key- | PrivKeyX448 X448.SecretKey -- ^ X448 private key- | PrivKeyEd25519 Ed25519.SecretKey -- ^ Ed25519 private key- | PrivKeyEd448 Ed448.SecretKey -- ^ Ed448 private key- deriving (Show,Eq)+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+ PrivKeyEC PrivKeyEC+ | -- | X25519 private key+ PrivKeyX25519 X25519.SecretKey+ | -- | X448 private key+ PrivKeyX448 X448.SecretKey+ | -- | Ed25519 private key+ PrivKeyEd25519 Ed25519.SecretKey+ | -- | Ed448 private key+ PrivKeyEd448 Ed448.SecretKey+ | -- | ML-DSA-44 private key+ PrivKeyMLDSA44 (PrivKeyMLDSA MLDSA.MLDSA44)+ | -- | ML-DSA-65 private key+ 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+-- that is what is meant. Each arm is @crypton@'s own 'debugShow' for that+-- key type, except the EC one, which is this module's.+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+ PrivKeyX448 p -> con "PrivKeyX448" $ debugShow p+ PrivKeyEd25519 p -> con "PrivKeyEd25519" $ debugShow p+ PrivKeyEd448 p -> con "PrivKeyEd448" $ debugShow p+ 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 ++ ")"+ instance ASN1Object PrivKey where fromASN1 = privkeyFromASN1 toASN1 = privkeyToASN1 privkeyFromASN1 :: [ASN1] -> Either String (PrivKey, [ASN1]) privkeyFromASN1 asn1 =- (mapFst PrivKeyRSA <$> rsaFromASN1 asn1) <!>- (mapFst PrivKeyDSA <$> dsaFromASN1 asn1) <!>- (mapFst PrivKeyEC <$> ecdsaFromASN1 asn1) <!>- newcurveFromASN1 asn1+ (mapFst PrivKeyRSA <$> rsaFromASN1 asn1)+ <!> rsaPSSFromASN1 asn1+ <!> (mapFst PrivKeyDSA <$> dsaFromASN1 asn1)+ <!> (mapFst PrivKeyEC <$> ecdsaFromASN1 asn1)+ <!> newcurveFromASN1 asn1 where mapFst f (a, b) = (f a, b) Left _ <!> b = b- a <!> _ = a+ a <!> _ = a rsaFromASN1 :: [ASN1] -> Either String (RSA.PrivateKey, [ASN1])-rsaFromASN1 (Start Sequence : IntVal 0 : IntVal n : IntVal e : IntVal d- : IntVal p : IntVal q : IntVal dP : IntVal dQ : IntVal qinv- : End Sequence : as) = pure (key, as)- where- key = RSA.PrivateKey (RSA.PublicKey (go n 1) n e) d p q dP dQ qinv- go m i- | 2 ^ (i * 8) > m = i- | otherwise = go m (i + 1)-rsaFromASN1 (Start Sequence : IntVal 0 : Start Sequence- : OID [1, 2, 840, 113549, 1, 1, 1] : Null : End Sequence- : OctetString bytes : End Sequence : as) = do- asn1 <- mapLeft failure (decodeASN1' BER bytes)+rsaFromASN1+ ( Start Sequence : IntVal 0 : IntVal n : IntVal e : IntVal d+ : IntVal p+ : IntVal q+ : IntVal dP+ : IntVal dQ+ : IntVal qinv+ : End Sequence+ : as+ ) = pure (key, as)+ where+ key = RSA.PrivateKey (RSA.PublicKey (go n 1) n e) d p q dP dQ qinv+ go m i+ | 2 ^ (i * 8) > m = i+ | otherwise = go m (i + 1)+rsaFromASN1+ ( Start Sequence : IntVal 0 : Start Sequence+ : OID [1, 2, 840, 113549, 1, 1, 1]+ : Null+ : End Sequence+ : OctetString bytes+ : End Sequence+ : as+ ) = do+ asn1 <- mapLeft failure (safeDecode $ decodeASN1' BER bytes) fmap (const as) <$> rsaFromASN1 asn1- where- failure = ("rsaFromASN1: " ++) . show+ where+ 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- : IntVal _ : IntVal x : End Sequence : as) =+dsaFromASN1+ ( Start Sequence : IntVal 0 : IntVal p : IntVal q : IntVal g+ : IntVal _+ : IntVal x+ : End Sequence+ : as+ ) = pure (DSA.PrivateKey (DSA.Params p g q) x, as)-dsaFromASN1 (Start Sequence : IntVal 0 : Start Sequence- : OID [1, 2, 840, 10040, 4, 1] : Start Sequence : IntVal p : IntVal q- : IntVal g : End Sequence : End Sequence : OctetString bytes- : End Sequence : as) = case decodeASN1' BER bytes of+dsaFromASN1+ ( Start Sequence : IntVal 0 : Start Sequence+ : OID [1, 2, 840, 10040, 4, 1]+ : Start Sequence+ : IntVal p+ : IntVal q+ : IntVal g+ : End Sequence+ : End Sequence+ : OctetString bytes+ : End Sequence+ : as+ ) = case safeDecode $ decodeASN1' BER bytes of Right [IntVal x] -> pure (DSA.PrivateKey (DSA.Params p g q) x, as) Right _ -> Left "DSA.PrivateKey.fromASN1: unexpected format"- Left e -> Left $ "DSA.PrivateKey.fromASN1: " ++ show e+ Left e -> Left $ "DSA.PrivateKey.fromASN1: " ++ e dsaFromASN1 _ = Left "DSA.PrivateKey.fromASN1: unexpected format" ecdsaFromASN1 :: [ASN1] -> Either String (PrivKeyEC, [ASN1])@@ -137,28 +480,43 @@ failure = Left $ failing $ "unknown curve " ++ show oid_ success = Right . flip PrivKeyEC_Named d mcurve = lookupByOID curvesOIDTable oid_- subgo (Start Sequence : IntVal 1 : Start Sequence- : OID [1, 2, 840, 10045, 1, 1] : IntVal p : End Sequence- : Start Sequence : OctetString a : OctetString b : BitString s- : End Sequence : OctetString g : IntVal o : IntVal c- : End Sequence : _) =+ subgo+ ( Start Sequence : IntVal 1 : Start Sequence+ : OID [1, 2, 840, 10045, 1, 1]+ : IntVal p+ : End Sequence+ : Start Sequence+ : OctetString a+ : OctetString b+ : BitString s+ : End Sequence+ : OctetString g+ : IntVal o+ : IntVal c+ : End Sequence+ : _+ ) = pure $ PrivKeyEC_Prime d a' b' p g' o c s'- where- a' = os2ip a- b' = os2ip b- g' = SerializedPoint g- s' = os2ip $ bitArrayGetData s+ where+ a' = os2ip a+ b' = os2ip b+ g' = SerializedPoint g+ s' = os2ip $ bitArrayGetData s subgo (Null : rest_) = subgo rest_ subgo [] = Left $ failing "curve is missing" subgo _ = Left $ failing "unexpected curve format"- go acc (Start Sequence : IntVal 0 : Start Sequence- : OID [1, 2, 840, 10045, 2, 1] : rest) = case rest' of+ go+ acc+ ( Start Sequence : IntVal 0 : Start Sequence+ : OID [1, 2, 840, 10045, 2, 1]+ : rest+ ) = case rest' of (OctetString bytes : rest'') -> do- asn1 <- mapLeft (failing . show) (decodeASN1' BER bytes)+ asn1 <- mapLeft failing (safeDecode $ decodeASN1' BER bytes) fmap (const rest'') <$> go (oid ++ acc) asn1 _ -> Left $ failing "unexpected EC format"- where- (oid, rest') = spanEnd 0 rest+ where+ (oid, rest') = spanEnd 0 rest go _ _ = Left $ failing "unexpected EC format" spanEnd :: Word -> [ASN1] -> ([ASN1], [ASN1])@@ -175,93 +533,242 @@ spanTag _ as = ([], as) newcurveFromASN1 :: [ASN1] -> Either String (PrivKey, [ASN1])-newcurveFromASN1 ( Start Sequence- : IntVal v- : Start Sequence- : OID oid- : End Sequence- : OctetString bs- : xs)- | isValidVersion v = do- let (_, ys) = containerWithTag 0 xs- case primitiveWithTag 1 ys of- (_, End Sequence : zs) ->- case getP oid of- Just (name, parse) -> do- let err s = Left (name ++ ".SecretKey.fromASN1: " ++ s)- case decodeASN1' BER bs of- Right [OctetString key] ->- case parse key of- CryptoPassed s -> Right (s, zs)- CryptoFailed e -> err ("invalid secret key: " ++ show e)- Right _ -> err "unexpected inner format"- Left e -> err (show e)- Nothing -> Left ("newcurveFromASN1: unexpected OID " ++ show oid)- _ -> Left "newcurveFromASN1: unexpected end format"- | otherwise = Left ("newcurveFromASN1: unexpected version: " ++ show v)- where- getP [1,3,101,110] = Just ("X25519", fmap PrivKeyX25519 . X25519.secretKey)- getP [1,3,101,111] = Just ("X448", fmap PrivKeyX448 . X448.secretKey)- getP [1,3,101,112] = Just ("Ed25519", fmap PrivKeyEd25519 . Ed25519.secretKey)- getP [1,3,101,113] = Just ("Ed448", fmap PrivKeyEd448 . Ed448.secretKey)- getP _ = Nothing- isValidVersion version = version >= 0 && version <= 1+newcurveFromASN1+ ( Start Sequence+ : IntVal v+ : Start Sequence+ : OID oid+ : End Sequence+ : OctetString bs+ : xs+ )+ | isValidVersion v = do+ let (_, ys) = containerWithTag 0 xs+ case primitiveWithTag 1 ys of+ (_, End Sequence : zs) ->+ case getP oid of+ Just (name, parse) -> do+ let err s = Left (name ++ ".SecretKey.fromASN1: " ++ s)+ case safeDecode $ decodeASN1' BER bs of+ Right [OctetString key] ->+ case parse key of+ CryptoPassed s -> Right (s, zs)+ CryptoFailed e -> err ("invalid secret key: " ++ show e)+ Right _ -> err "unexpected inner format"+ Left e -> err e+ Nothing -> case getMLDSA oid of+ Just (name, parse) ->+ case safeDecode $ decodeASN1' BER bs of+ Right inner -> (\k -> (k, zs)) <$> parse inner+ Left e -> Left (name ++ ".SigningKey.fromASN1: " ++ e)+ Nothing -> Left ("newcurveFromASN1: unexpected OID " ++ show oid)+ _ -> Left "newcurveFromASN1: unexpected end format"+ | otherwise = Left ("newcurveFromASN1: unexpected version: " ++ show v)+ where+ getP [1, 3, 101, 110] = Just ("X25519", fmap PrivKeyX25519 . X25519.secretKey)+ getP [1, 3, 101, 111] = Just ("X448", fmap PrivKeyX448 . X448.secretKey)+ getP [1, 3, 101, 112] = Just ("Ed25519", fmap PrivKeyEd25519 . Ed25519.secretKey)+ getP [1, 3, 101, 113] = Just ("Ed448", fmap PrivKeyEd448 . Ed448.secretKey)+ getP _ = Nothing+ getMLDSA [2, 16, 840, 1, 101, 3, 4, 3, 17] =+ Just+ ( "ML-DSA-44"+ , mldsaFromASN1 (Proxy :: Proxy MLDSA.MLDSA44) PrivKeyMLDSA44 "ML-DSA-44"+ )+ getMLDSA [2, 16, 840, 1, 101, 3, 4, 3, 18] =+ Just+ ( "ML-DSA-65"+ , mldsaFromASN1 (Proxy :: Proxy MLDSA.MLDSA65) PrivKeyMLDSA65 "ML-DSA-65"+ )+ getMLDSA [2, 16, 840, 1, 101, 3, 4, 3, 19] =+ Just+ ( "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 _ = Left "newcurveFromASN1: unexpected format" +-- | The private key of RFC 9881 Section 6: a CHOICE of the seed, tagged+-- [0], the expanded key, or both. A seed is expanded into the key; with+-- both, the expanded key must be what the seed expands to. Which of the+-- three it was is kept, so that 'mldsaToASN1' writes back what was read.+mldsaFromASN1+ :: MLDSA.MLDSA p+ => proxy p+ -> (PrivKeyMLDSA p -> PrivKey)+ -> String+ -> [ASN1]+ -> Either String PrivKey+mldsaFromASN1 p con name inner = case inner of+ [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 MLKeyBoth seed+ sk <- fromExpanded expanded+ if privkeyMLDSA_key k == sk+ then Right (con k)+ else err "seed and expandedKey do not match"+ _ -> err "unexpected inner format"+ where+ err s = Left (name ++ ".SigningKey.fromASN1: " ++ s)+ fromSeed form seed = case privkeyMLDSAFromSeed p form seed of+ CryptoPassed k -> Right k+ CryptoFailed e -> err ("invalid seed: " ++ show e)+ fromExpanded expanded = case MLDSA.signingKey expanded of+ 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-containerWithTag _ xs = ([], xs)+containerWithTag _ xs = ([], xs) primitiveWithTag :: ASN1Tag -> [ASN1] -> (Maybe B.ByteString, [ASN1]) primitiveWithTag etag (Other _ atag bs : xs) | etag == atag = (Just bs, xs)-primitiveWithTag _ xs = (Nothing, xs)+primitiveWithTag _ xs = (Nothing, xs) 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-privkeyToASN1 (PrivKeyX448 k) = newcurveToASN1 [1,3,101,111] k-privkeyToASN1 (PrivKeyEd25519 k) = newcurveToASN1 [1,3,101,112] k-privkeyToASN1 (PrivKeyEd448 k) = newcurveToASN1 [1,3,101,113] k+privkeyToASN1 (PrivKeyX25519 k) = newcurveToASN1 [1, 3, 101, 110] k+privkeyToASN1 (PrivKeyX448 k) = newcurveToASN1 [1, 3, 101, 111] k+privkeyToASN1 (PrivKeyEd25519 k) = newcurveToASN1 [1, 3, 101, 112] k+privkeyToASN1 (PrivKeyEd448 k) = newcurveToASN1 [1, 3, 101, 113] k+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 = (++)- [ Start Sequence, IntVal 0, IntVal n, IntVal e, IntVal d, IntVal p- , IntVal q, IntVal dP, IntVal dQ, IntVal qinv, End Sequence- ]+rsaToASN1 key =+ (++)+ [ Start Sequence+ , IntVal 0+ , IntVal n+ , IntVal e+ , IntVal d+ , IntVal p+ , IntVal q+ , IntVal dP+ , IntVal dQ+ , IntVal qinv+ , End Sequence+ ] where RSA.PrivateKey (RSA.PublicKey _ n e) d p q dP dQ qinv = key dsaToASN1 :: DSA.PrivateKey -> ASN1S-dsaToASN1 (DSA.PrivateKey params@(DSA.Params p g q) y) = (++)- [ Start Sequence, IntVal 0, IntVal p, IntVal q, IntVal g, IntVal x- , IntVal y, End Sequence- ]+dsaToASN1 (DSA.PrivateKey params@(DSA.Params p g q) y) =+ (++)+ [ Start Sequence+ , IntVal 0+ , IntVal p+ , IntVal q+ , IntVal g+ , IntVal x+ , IntVal y+ , End Sequence+ ] where x = DSA.calculatePublic params y ecdsaToASN1 :: PrivKeyEC -> ASN1S-ecdsaToASN1 (PrivKeyEC_Named curveName d) = (++)- [ Start Sequence, IntVal 1, OctetString (i2osp d)- , Start (Container Context 0), OID oid, End (Container Context 0)- , End Sequence- ]+-- RFC 5915: the private key is as long as the curve order.+ecdsaToASN1 (PrivKeyEC_Named curveName d) =+ (++)+ [ Start Sequence+ , IntVal 1+ , OctetString (i2ospOf_ (numBytes order) d)+ , Start (Container Context 0)+ , OID oid+ , End (Container Context 0)+ , End Sequence+ ] where+ order = ECC.ecc_n $ ECC.common_curve $ ECC.getCurveByName curveName err = error . ("ECDSA.PrivateKey.toASN1: " ++)- oid = fromMaybe (err $ "missing named curve " ++ show curveName)- (lookupOID curvesOIDTable curveName)-ecdsaToASN1 (PrivKeyEC_Prime d a b p g o c s) = (++)- [ Start Sequence, IntVal 1, OctetString (i2osp d)- , Start (Container Context 0), Start Sequence, IntVal 1- , Start Sequence, OID [1, 2, 840, 10045, 1, 1], IntVal p, End Sequence- , Start Sequence, OctetString a', OctetString b', BitString s'- , End Sequence, OctetString g' , IntVal o, IntVal c, End Sequence- , End (Container Context 0), End Sequence- ]+ oid =+ fromMaybe+ (err $ "missing named curve " ++ show curveName)+ (lookupOID curvesOIDTable curveName)+ecdsaToASN1 (PrivKeyEC_Prime d a b p g o c s) =+ (++)+ [ Start Sequence+ , IntVal 1+ , OctetString (i2ospOf_ (numBytes o) d)+ , Start (Container Context 0)+ , Start Sequence+ , IntVal 1+ , Start Sequence+ , OID [1, 2, 840, 10045, 1, 1]+ , IntVal p+ , End Sequence+ , Start Sequence+ , OctetString a'+ , OctetString b'+ , BitString s'+ , End Sequence+ , OctetString g'+ , IntVal o+ , IntVal c+ , End Sequence+ , End (Container Context 0)+ , End Sequence+ ] where a' = i2osp a b' = i2osp b@@ -271,22 +778,82 @@ bytes = i2osp s newcurveToASN1 :: ByteArrayAccess key => OID -> key -> ASN1S-newcurveToASN1 oid key = (++)- [ Start Sequence, IntVal 0, Start Sequence, OID oid, End Sequence- , OctetString (encodeASN1' DER [OctetString $ convert key])- , End Sequence- ]+newcurveToASN1 oid key =+ (++)+ [ Start Sequence+ , IntVal 0+ , Start Sequence+ , OID oid+ , End Sequence+ , OctetString (encodeASN1' DER [OctetString $ convert key])+ , End Sequence+ ] +-- | The inverse of 'mldsaFromASN1': the form the key is in is the form it+-- is written in, so reading a key and writing it again gives back the+-- bytes it came from.+mldsaToASN1 :: OID -> PrivKeyMLDSA p -> ASN1S+mldsaToASN1 oid k =+ (++)+ [ Start Sequence+ , IntVal 0+ , Start Sequence+ , OID oid+ , End Sequence+ , OctetString (encodeASN1' DER inner)+ , End Sequence+ ]+ where+ inner = case k of+ PrivKeyMLDSA_Seed s _ -> [Other Context 0 (convert s)]+ PrivKeyMLDSA_Expanded sk -> [OctetString (convert sk)]+ PrivKeyMLDSA_Both s sk ->+ [ Start Sequence+ , OctetString (convert s)+ , OctetString (convert sk)+ , 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 -- | Convert a Private key to the Public Key Algorithm type privkeyToAlg :: PrivKey -> PubKeyALG-privkeyToAlg (PrivKeyRSA _) = PubKeyALG_RSA-privkeyToAlg (PrivKeyDSA _) = PubKeyALG_DSA-privkeyToAlg (PrivKeyEC _) = PubKeyALG_EC-privkeyToAlg (PrivKeyX25519 _) = PubKeyALG_X25519-privkeyToAlg (PrivKeyX448 _) = PubKeyALG_X448-privkeyToAlg (PrivKeyEd25519 _) = PubKeyALG_Ed25519-privkeyToAlg (PrivKeyEd448 _) = PubKeyALG_Ed448+privkeyToAlg (PrivKeyRSA _) = PubKeyALG_RSA+privkeyToAlg (PrivKeyRSAPSS _ _) = PubKeyALG_RSAPSS+privkeyToAlg (PrivKeyDSA _) = PubKeyALG_DSA+privkeyToAlg (PrivKeyEC _) = PubKeyALG_EC+privkeyToAlg (PrivKeyX25519 _) = PubKeyALG_X25519+privkeyToAlg (PrivKeyX448 _) = PubKeyALG_X448+privkeyToAlg (PrivKeyEd25519 _) = PubKeyALG_Ed25519+privkeyToAlg (PrivKeyEd448 _) = PubKeyALG_Ed448+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@@ -6,78 +8,132 @@ -- Portability : unknown -- -- Public key handling in X.509 infrastructure----module Data.X509.PublicKey- ( PubKey(..)- , PubKeyEC(..)- , SerializedPoint(..)- , pubkeyToAlg- ) where+module Data.X509.PublicKey (+ PubKey (..),+ PubKeyEC (..),+ PubKeyDH,+ dhPublicKey,+ pubkeyDH_p,+ pubkeyDH_g,+ pubkeyDH_q,+ pubkeyDH_j,+ pubkeyDH_validation,+ pubkeyDH_y,+ SerializedPoint (..),+ pubkeyToAlg,+) where -import Data.ASN1.Types-import Data.ASN1.Encoding import Data.ASN1.BinaryEncoding import Data.ASN1.BitArray+import Data.ASN1.Encoding+import Data.ASN1.Types import Data.Bits import Data.ByteArray (convert) import Data.ByteString (ByteString) +import Data.X509.AlgorithmIdentifier import Data.X509.Internal import Data.X509.OID-import Data.X509.AlgorithmIdentifier -import Crypto.Error (CryptoFailable(..))-import qualified Crypto.PubKey.RSA.Types as RSA-import qualified Crypto.PubKey.DSA as DSA-import qualified Crypto.PubKey.ECC.Types as ECC+import Crypto.Error (CryptoFailable (..))+import Crypto.Number.Basic (numBytes)+import Crypto.Number.Serialize (i2osp, i2ospOf_, os2ip) import qualified Crypto.PubKey.Curve25519 as X25519-import qualified Crypto.PubKey.Curve448 as X448-import qualified Crypto.PubKey.Ed25519 as Ed25519-import qualified Crypto.PubKey.Ed448 as Ed448-import Crypto.Number.Basic (numBytes)-import Crypto.Number.Serialize (os2ip)+import qualified Crypto.PubKey.Curve448 as X448+import qualified Crypto.PubKey.DSA as DSA+import qualified Crypto.PubKey.ECC.Types as ECC+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 import qualified Data.ByteString as B -- | Serialized Elliptic Curve Point newtype SerializedPoint = SerializedPoint ByteString- deriving (Show,Eq)+ deriving (Show, Eq) -- | Elliptic Curve Public Key -- -- TODO: missing support for binary curve.-data PubKeyEC =- PubKeyEC_Prime- { pubkeyEC_pub :: SerializedPoint- , pubkeyEC_a :: Integer- , pubkeyEC_b :: Integer- , pubkeyEC_prime :: Integer+data PubKeyEC+ = PubKeyEC_Prime+ { pubkeyEC_pub :: SerializedPoint+ , pubkeyEC_a :: Integer+ , pubkeyEC_b :: Integer+ , pubkeyEC_prime :: Integer , pubkeyEC_generator :: SerializedPoint- , pubkeyEC_order :: Integer- , pubkeyEC_cofactor :: Integer- , pubkeyEC_seed :: Integer+ , pubkeyEC_order :: Integer+ , pubkeyEC_cofactor :: Integer+ , pubkeyEC_seed :: Integer } | PubKeyEC_Named- { pubkeyEC_name :: ECC.CurveName- , pubkeyEC_pub :: SerializedPoint+ { pubkeyEC_name :: ECC.CurveName+ , pubkeyEC_pub :: SerializedPoint }- deriving (Show,Eq)+ 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 =- PubKeyRSA RSA.PublicKey -- ^ RSA public key- | PubKeyDSA DSA.PublicKey -- ^ DSA public key- | PubKeyDH (Integer,Integer,Integer,Maybe Integer,([Word8], Integer))- -- ^ DH format with (p,g,q,j,(seed,pgenCounter))- | PubKeyEC PubKeyEC -- ^ EC public key- | PubKeyX25519 X25519.PublicKey -- ^ X25519 public key- | PubKeyX448 X448.PublicKey -- ^ X448 public key- | PubKeyEd25519 Ed25519.PublicKey -- ^ Ed25519 public key- | PubKeyEd448 Ed448.PublicKey -- ^ Ed448 public key- | PubKeyUnknown OID B.ByteString -- ^ unrecognized format- deriving (Show,Eq)+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+ | -- | X9.42 DH public key+ PubKeyDH PubKeyDH+ | -- | EC public key+ PubKeyEC PubKeyEC+ | -- | X25519 public key+ PubKeyX25519 X25519.PublicKey+ | -- | X448 public key+ PubKeyX448 X448.PublicKey+ | -- | Ed25519 public key+ PubKeyEd25519 Ed25519.PublicKey+ | -- | Ed448 public key+ PubKeyEd448 Ed448.PublicKey+ | -- | ML-DSA-44 public key+ PubKeyMLDSA44 (MLDSA.VerificationKey MLDSA.MLDSA44)+ | -- | ML-DSA-65 public key+ 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) -- Public key are in the format: --@@ -87,109 +143,205 @@ -- BitString -- End Sequence instance ASN1Object PubKey where- fromASN1 (Start Sequence:Start Sequence:OID pkalg:xs)+ fromASN1 (Start Sequence : Start Sequence : OID pkalg : xs) | pkalg == getObjectID PubKeyALG_RSA = case removeNull xs of- End Sequence:BitString bits:End Sequence:xs2 -> decodeASN1Err "RSA" bits xs2 (toPubKeyRSA . rsaPubFromASN1)+ 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_DSA =+ | 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:BitString bits:End Sequence:xs2 ->- decodeASN1Err "DSA" bits xs2 (\l -> case l of- [IntVal dsapub] ->- let pubkey = DSA.PublicKey { DSA.public_params = DSA.Params { DSA.params_p = p- , DSA.params_q = q- , DSA.params_g = g- }- , DSA.public_y = dsapub }- in Right (PubKeyDSA pubkey, [])- _ -> Left "fromASN1: X509.PubKey: unknown DSA format"- )+ Start Sequence : IntVal p : IntVal q : IntVal g : End Sequence : End Sequence+ : BitString bits+ : End Sequence+ : xs2 ->+ decodeASN1Err+ "DSA"+ bits+ xs2+ ( \l -> case l of+ [IntVal dsapub] ->+ let pubkey =+ DSA.PublicKey+ { DSA.public_params =+ DSA.Params+ { DSA.params_p = p+ , DSA.params_q = q+ , DSA.params_g = g+ }+ , DSA.public_y = dsapub+ }+ in Right (PubKeyDSA pubkey, [])+ _ -> 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 ->+ OID curveOid : End Sequence : BitString bits : End Sequence : xs2 -> case lookupByOID curvesOIDTable curveOid of Just curveName -> Right (PubKeyEC $ PubKeyEC_Named curveName (bitArrayToPoint bits), xs2)- Nothing -> Left ("fromASN1: X509.Pubkey: EC unknown curve " ++ show curveOid)+ Nothing -> Left ("fromASN1: X509.Pubkey: EC unknown curve " ++ show curveOid) Start Sequence- :IntVal 1- :Start Sequence- :OID [1,2,840,10045,1,1]- :IntVal prime- :End Sequence- :Start Sequence- :OctetString a- :OctetString b- :BitString seed- :End Sequence- :OctetString generator- :IntVal order- :IntVal cofactor- :End Sequence- :End Sequence- :BitString pub- :End Sequence- :xs2 ->- Right (PubKeyEC $ PubKeyEC_Prime- { pubkeyEC_pub = bitArrayToPoint pub- , pubkeyEC_a = os2ip a- , pubkeyEC_b = os2ip b- , pubkeyEC_prime = prime- , pubkeyEC_generator = SerializedPoint generator- , pubkeyEC_order = order- , pubkeyEC_cofactor = cofactor- , pubkeyEC_seed = os2ip $ bitArrayGetData seed- }, xs2)+ : IntVal 1+ : Start Sequence+ : OID [1, 2, 840, 10045, 1, 1]+ : IntVal prime+ : End Sequence+ : Start Sequence+ : OctetString a+ : OctetString b+ : BitString seed+ : End Sequence+ : OctetString generator+ : IntVal order+ : IntVal cofactor+ : End Sequence+ : End Sequence+ : BitString pub+ : End Sequence+ : xs2 ->+ Right+ ( PubKeyEC $+ PubKeyEC_Prime+ { pubkeyEC_pub = bitArrayToPoint pub+ , pubkeyEC_a = os2ip a+ , pubkeyEC_b = os2ip b+ , pubkeyEC_prime = prime+ , pubkeyEC_generator = SerializedPoint generator+ , pubkeyEC_order = order+ , pubkeyEC_cofactor = cofactor+ , pubkeyEC_seed = os2ip $ bitArrayGetData seed+ }+ , xs2+ ) _ -> Left $ "fromASN1: X509.PubKey: unknown EC format: " ++ show xs- | pkalg == getObjectID PubKeyALG_X25519 =+ | pkalg == getObjectID PubKeyALG_X25519 = case xs of- End Sequence:BitString bits:End Sequence:xs2 -> decodeCF "X25519" PubKeyX25519 bits xs2 X25519.publicKey+ End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "X25519" PubKeyX25519 bits xs2 X25519.publicKey _ -> Left ("fromASN1: X509.PubKey: unknown X25519 format: " ++ show xs)- | pkalg == getObjectID PubKeyALG_X448 =+ | pkalg == getObjectID PubKeyALG_X448 = case xs of- End Sequence:BitString bits:End Sequence:xs2 -> decodeCF "X448" PubKeyX448 bits xs2 X448.publicKey+ End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "X448" PubKeyX448 bits xs2 X448.publicKey _ -> Left ("fromASN1: X509.PubKey: unknown X448 format: " ++ show xs)- | pkalg == getObjectID PubKeyALG_Ed25519 =+ | pkalg == getObjectID PubKeyALG_Ed25519 = case xs of- End Sequence:BitString bits:End Sequence:xs2 -> decodeCF "Ed25519" PubKeyEd25519 bits xs2 Ed25519.publicKey+ End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "Ed25519" PubKeyEd25519 bits xs2 Ed25519.publicKey _ -> Left ("fromASN1: X509.PubKey: unknown Ed25519 format: " ++ show xs)- | pkalg == getObjectID PubKeyALG_Ed448 =+ | pkalg == getObjectID PubKeyALG_Ed448 = case xs of- End Sequence:BitString bits:End Sequence:xs2 -> decodeCF "Ed448" PubKeyEd448 bits xs2 Ed448.publicKey+ End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "Ed448" PubKeyEd448 bits xs2 Ed448.publicKey _ -> Left ("fromASN1: X509.PubKey: unknown Ed448 format: " ++ show xs)- | otherwise = Left $ "fromASN1: unknown public key OID: " ++ show pkalg- where decodeASN1Err format bits xs2 f =- case decodeASN1' BER (bitArrayGetData bits) of- Left err -> Left ("fromASN1: X509.PubKey " ++ format ++ " bitarray cannot be parsed: " ++ show err)- Right s -> case f s of- Left err -> Left err- Right (r, xsinner) -> Right (r, xsinner ++ xs2)- toPubKeyRSA = either Left (\(rsaKey, r) -> Right (PubKeyRSA rsaKey, r))-- bitArrayToPoint = SerializedPoint . bitArrayGetData+ -- RFC 9881 Section 4: the parameters are absent and the BIT STRING+ -- is the raw public key.+ | pkalg == getObjectID PubKeyALG_MLDSA44 =+ case xs of+ End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "ML-DSA-44" PubKeyMLDSA44 bits xs2 MLDSA.verificationKey+ _ -> Left ("fromASN1: X509.PubKey: unknown ML-DSA-44 format: " ++ show xs)+ | pkalg == getObjectID PubKeyALG_MLDSA65 =+ case xs of+ End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "ML-DSA-65" PubKeyMLDSA65 bits xs2 MLDSA.verificationKey+ _ -> Left ("fromASN1: X509.PubKey: unknown ML-DSA-65 format: " ++ show xs)+ | pkalg == getObjectID PubKeyALG_MLDSA87 =+ 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 ->+ Right (PubKeyUnknown pkalg (bitArrayGetData bits), xs2)+ _ -> Left ("fromASN1: X509.PubKey: unknown format for " ++ show pkalg)+ where+ dropParams 0 (End Sequence : r) = r+ dropParams n (Start _ : r) = dropParams (n + 1) r+ dropParams n (End _ : r) = dropParams (n - 1) r+ dropParams n (_ : r) = dropParams n r+ dropParams _ [] = []+ decodeASN1Err format bits xs2 f =+ case safeDecode (decodeASN1' BER (bitArrayGetData bits)) of+ Left err ->+ Left+ ("fromASN1: X509.PubKey " ++ format ++ " bitarray cannot be parsed: " ++ err)+ Right s -> case f s of+ Left err -> Left err+ Right (r, []) -> Right (r, xs2)+ -- anything after the key must not leak into the outer stream+ 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)) - removeNull (Null:r) = r- removeNull l = l+ bitArrayToPoint = SerializedPoint . bitArrayGetData - decodeCF format c bits xs2 f = case f (bitArrayGetData bits) of- CryptoPassed pk -> Right (c pk, xs2)- CryptoFailed err -> Left ("fromASN1: X509.PubKey " ++ format ++ " bitarray contains an invalid public key: " ++ show err)+ removeNull (Null : r) = r+ removeNull l = l + decodeCF format c bits xs2 f = case f (bitArrayGetData bits) of+ CryptoPassed pk -> Right (c pk, xs2)+ CryptoFailed err ->+ Left+ ( "fromASN1: X509.PubKey "+ ++ format+ ++ " bitarray contains an invalid public key: "+ ++ show err+ ) fromASN1 l = Left ("fromASN1: X509.PubKey: unknown format:" ++ show l) toASN1 a = \xs -> encodePK a ++ xs -- | Convert a Public key to the Public Key Algorithm type pubkeyToAlg :: PubKey -> PubKeyALG-pubkeyToAlg (PubKeyRSA _) = PubKeyALG_RSA-pubkeyToAlg (PubKeyDSA _) = PubKeyALG_DSA-pubkeyToAlg (PubKeyDH _) = PubKeyALG_DH-pubkeyToAlg (PubKeyEC _) = PubKeyALG_EC-pubkeyToAlg (PubKeyX25519 _) = PubKeyALG_X25519-pubkeyToAlg (PubKeyX448 _) = PubKeyALG_X448-pubkeyToAlg (PubKeyEd25519 _) = PubKeyALG_Ed25519-pubkeyToAlg (PubKeyEd448 _) = PubKeyALG_Ed448+pubkeyToAlg (PubKeyRSA _) = PubKeyALG_RSA+pubkeyToAlg (PubKeyRSAPSS _ _) = PubKeyALG_RSAPSS+pubkeyToAlg (PubKeyDSA _) = PubKeyALG_DSA+pubkeyToAlg (PubKeyDH _) = PubKeyALG_DH+pubkeyToAlg (PubKeyEC _) = PubKeyALG_EC+pubkeyToAlg (PubKeyX25519 _) = PubKeyALG_X25519+pubkeyToAlg (PubKeyX448 _) = PubKeyALG_X448+pubkeyToAlg (PubKeyEd25519 _) = PubKeyALG_Ed25519+pubkeyToAlg (PubKeyEd448 _) = PubKeyALG_Ed448+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]@@ -197,68 +349,129 @@ where pkalg = OID $ getObjectID $ pubkeyToAlg key encodeInner (PubKeyRSA pubkey) =- asn1Container Sequence [pkalg,Null] ++ [BitString $ toBitArray bits 0]- where bits = encodeASN1' DER $ rsaPubToASN1 pubkey []+ 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- dsaseq = asn1Container Sequence [IntVal (DSA.params_p params)- ,IntVal (DSA.params_q params)- ,IntVal (DSA.params_g params)]+ dsaseq =+ asn1Container+ Sequence+ [ IntVal (DSA.params_p params)+ , IntVal (DSA.params_q params)+ , IntVal (DSA.params_g params)+ ] params = DSA.public_params pubkey- bits = encodeASN1' DER [IntVal $ DSA.public_y pubkey]+ bits = encodeASN1' DER [IntVal $ DSA.public_y pubkey] encodeInner (PubKeyEC (PubKeyEC_Named curveName (SerializedPoint bits))) =- asn1Container Sequence [pkalg,OID eOid] ++ [BitString $ toBitArray bits 0]+ asn1Container Sequence [pkalg, OID eOid] ++ [BitString $ toBitArray bits 0] where eOid = case lookupOID curvesOIDTable curveName of- Just oid -> oid- _ -> error ("undefined curve OID: " ++ show curveName)- encodeInner (PubKeyEC (PubKeyEC_Prime {})) =- error "encodeInner: unimplemented public key EC_Prime"- encodeInner (PubKeyX25519 pubkey) =+ Just oid -> oid+ _ -> error ("undefined curve OID: " ++ show curveName)+ encodeInner (PubKeyEC k@PubKeyEC_Prime{}) =+ asn1Container Sequence ([pkalg] ++ params) ++ [BitString $ toBitArray pub 0]+ where+ SerializedPoint pub = pubkeyEC_pub k+ SerializedPoint gen = pubkeyEC_generator k+ size = numBytes (pubkeyEC_prime k)+ params =+ asn1Container Sequence $+ [IntVal 1]+ ++ asn1Container+ Sequence+ [OID [1, 2, 840, 10045, 1, 1], IntVal (pubkeyEC_prime k)]+ ++ asn1Container+ Sequence+ [ OctetString (i2ospOf_ size (pubkeyEC_a k))+ , OctetString (i2ospOf_ size (pubkeyEC_b k))+ , BitString $ toBitArray (i2osp (pubkeyEC_seed k)) 0+ ]+ ++ [ OctetString gen+ , IntVal (pubkeyEC_order k)+ , IntVal (pubkeyEC_cofactor k)+ ]+ encodeInner (PubKeyX25519 pubkey) = asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]- encodeInner (PubKeyX448 pubkey) =+ encodeInner (PubKeyX448 pubkey) = asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]- encodeInner (PubKeyEd25519 pubkey) =+ encodeInner (PubKeyEd25519 pubkey) = asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]- encodeInner (PubKeyEd448 pubkey) =+ encodeInner (PubKeyEd448 pubkey) = asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]- encodeInner (PubKeyDH _) = error "encodeInner: unimplemented public key DH"+ encodeInner (PubKeyMLDSA44 pubkey) =+ asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]+ encodeInner (PubKeyMLDSA65 pubkey) =+ asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]+ encodeInner (PubKeyMLDSA87 pubkey) =+ asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]+ 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]+ asn1Container Sequence [pkalg, Null] ++ [BitString $ toBitArray l 0] rsaPubToASN1 :: RSA.PublicKey -> [ASN1] -> [ASN1] rsaPubToASN1 pubkey xs =- Start Sequence : IntVal (RSA.public_n pubkey) : IntVal (RSA.public_e pubkey) : End Sequence : xs+ Start Sequence+ : IntVal (RSA.public_n pubkey)+ : IntVal (RSA.public_e pubkey)+ : End Sequence+ : xs rsaPubFromASN1 :: [ASN1] -> Either String (RSA.PublicKey, [ASN1])-rsaPubFromASN1 (Start Sequence:IntVal smodulus:IntVal pubexp:End Sequence:xs) =+rsaPubFromASN1 (Start Sequence : IntVal smodulus : IntVal pubexp : End Sequence : xs) = Right (pub, xs) where- pub = RSA.PublicKey { RSA.public_size = numBytes modulus- , RSA.public_n = modulus- , RSA.public_e = pubexp- }+ pub =+ RSA.PublicKey+ { RSA.public_size = numBytes modulus+ , RSA.public_n = modulus+ , RSA.public_e = pubexp+ } -- some bad implementation will not serialize ASN.1 integer properly, leading -- to negative modulus. if that's the case, we correct it. modulus = toPositive smodulus--rsaPubFromASN1 ( Start Sequence- : IntVal ver- : Start Sequence- : OID oid- : Null- : End Sequence- : OctetString bs- : xs- )- | ver /= 0 = Left "rsaPubFromASN1: Invalid version, expecting 0"- | oid /= [1,2,840,113549,1,1,1] =- Left "rsaPubFromASN1: invalid OID"- | otherwise =- let inner = either strError rsaPubFromASN1 $ decodeASN1' BER bs- strError = Left . ("fromASN1: RSA.PublicKey: " ++) . show- in either Left (\(k, _) -> Right (k, xs)) inner+rsaPubFromASN1+ ( Start Sequence+ : IntVal ver+ : Start Sequence+ : OID oid+ : Null+ : End Sequence+ : OctetString bs+ : xs+ )+ | ver /= 0 = Left "rsaPubFromASN1: Invalid version, expecting 0"+ | oid /= [1, 2, 840, 113549, 1, 1, 1] =+ Left "rsaPubFromASN1: invalid OID"+ | otherwise =+ let inner = either strError rsaPubFromASN1 $ safeDecode $ decodeASN1' BER bs+ strError = Left . ("fromASN1: RSA.PublicKey: " ++)+ in case inner of+ Right (k, []) -> Right (k, xs)+ Right _ -> Left "fromASN1: RSA.PublicKey: trailing data"+ Left e -> Left e rsaPubFromASN1 _ = Left "fromASN1: RSA.PublicKey: unexpected format" @@ -266,14 +479,21 @@ -- to negative modulus. toPositive :: Integer -> Integer toPositive int- | int < 0 = uintOfBytes $ bytesOfInt int+ | int < 0 = uintOfBytes $ bytesOfInt int | otherwise = int where uintOfBytes = foldl (\acc n -> (acc `shiftL` 8) + fromIntegral n) 0 bytesOfInt :: Integer -> [Word8]- bytesOfInt n = if testBit (head nints) 7 then nints else 0xff : nints- where nints = reverse $ plusOne $ reverse $ map complement $ bytesOfUInt (abs n)- plusOne [] = [1]- plusOne (x:xs) = if x == 0xff then 0 : plusOne xs else (x+1) : xs+ bytesOfInt n = case nints of+ h : _ | testBit h 7 -> nints+ _ -> 0xff : nints+ where+ nints = reverse $ plusOne $ reverse $ map complement $ bytesOfUInt (abs n)+ plusOne [] = [1]+ plusOne (x : xs) = if x == 0xff then 0 : plusOne xs else (x + 1) : xs bytesOfUInt x = reverse (list x)- where list i = if i <= 0xff then [fromIntegral i] else (fromIntegral i .&. 0xff) : list (i `shiftR` 8)+ where+ list i =+ if i <= 0xff+ then [fromIntegral i]+ else (fromIntegral i .&. 0xff) : list (i `shiftR` 8)
Data/X509/Signed.hs view
@@ -21,59 +21,70 @@ -- -- Signed represent the pure data type for compliant cases, and SignedExact -- the real world situation of having to deal with compliant and non-compliant cases.----module Data.X509.Signed- (+module Data.X509.Signed ( -- * Types- Signed(..)- , SignedExact+ Signed (..),+ SignedExact,+ -- * SignedExact to Signed- , getSigned- , getSignedData+ getSigned,+ getSignedData,+ -- * Marshalling function- , encodeSignedObject- , decodeSignedObject+ encodeSignedObject,+ decodeSignedObject,+ -- * Object to Signed and SignedExact- , objectToSignedExact- , objectToSignedExactF- , objectToSigned- , signedToExact- ) where+ objectToSignedExact,+ objectToSignedExactF,+ objectToSigned,+ signedToExact,+) where import Control.Arrow (first)+import Data.ASN1.BinaryEncoding+import qualified Data.ASN1.BinaryEncoding.Raw as Raw (toByteString)+import Data.ASN1.BitArray+import Data.ASN1.Encoding+import Data.ASN1.Stream+import Data.ASN1.Types import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.X509.AlgorithmIdentifier-import Data.ASN1.Types-import Data.ASN1.Encoding-import Data.ASN1.BinaryEncoding-import Data.ASN1.Stream-import Data.ASN1.BitArray-import qualified Data.ASN1.BinaryEncoding.Raw as Raw (toByteString)+import Data.X509.Internal (safeDecode) -- | Represent a signed object using a traditional X509 structure. -- -- When dealing with external certificate, use the SignedExact structure -- not this one. data (Show a, Eq a, ASN1Object a) => Signed a = Signed- { signedObject :: a -- ^ Object to sign- , signedAlg :: SignatureALG -- ^ Signature Algorithm used- , signedSignature :: B.ByteString -- ^ Signature as bytes- } deriving (Show, Eq)+ { signedObject :: a+ -- ^ Object to sign+ , signedAlg :: SignatureALG+ -- ^ Signature Algorithm used+ , signedSignature :: B.ByteString+ -- ^ Signature as bytes+ }+ deriving (Show, Eq) -- | Represent the signed object plus the raw data that we need to -- keep around for non compliant case to be able to verify signature. data (Show a, Eq a, ASN1Object a) => SignedExact a = SignedExact- { getSigned :: Signed a -- ^ get the decoded Signed data- , exactObjectRaw :: B.ByteString -- ^ The raw representation of the object a- -- TODO: in later version, replace with offset in exactRaw- , encodeSignedObject :: B.ByteString -- ^ The raw representation of the whole signed structure- } deriving (Show, Eq)+ { getSigned :: Signed a+ -- ^ get the decoded Signed data+ , exactObjectRaw :: B.ByteString+ -- ^ The raw representation of the object a+ -- TODO: in later version, replace with offset in exactRaw+ , encodeSignedObject :: B.ByteString+ -- ^ The raw representation of the whole signed structure+ }+ deriving (Show, Eq) -- | Get the signed data for the signature-getSignedData :: (Show a, Eq a, ASN1Object a)- => SignedExact a- -> B.ByteString+getSignedData+ :: (Show a, Eq a, ASN1Object a)+ => SignedExact a+ -> B.ByteString getSignedData = exactObjectRaw -- | make a 'SignedExact' copy of a 'Signed' object@@ -82,18 +93,23 @@ -- encoded object to have been made on a compliant DER ASN1 implementation. -- -- It's better to use 'objectToSignedExact' instead of this.-signedToExact :: (Show a, Eq a, ASN1Object a)- => Signed a- -> SignedExact a+signedToExact+ :: (Show a, Eq a, ASN1Object a)+ => Signed a+ -> SignedExact a signedToExact signed = sExact- where (sExact, ()) = objectToSignedExact fakeSigFunction (signedObject signed)- fakeSigFunction _ = (signedSignature signed, signedAlg signed, ())+ where+ (sExact, ()) = objectToSignedExact fakeSigFunction (signedObject signed)+ fakeSigFunction _ = (signedSignature signed, signedAlg signed, ()) -- | Transform an object into a 'SignedExact' object-objectToSignedExact :: (Show a, Eq a, ASN1Object a)- => (ByteString -> (ByteString, SignatureALG, r)) -- ^ signature function- -> a -- ^ object to sign- -> (SignedExact a, r)+objectToSignedExact+ :: (Show a, Eq a, ASN1Object a)+ => (ByteString -> (ByteString, SignatureALG, r))+ -- ^ signature function+ -> a+ -- ^ object to sign+ -> (SignedExact a, r) objectToSignedExact signatureFunction object = (signedExact, val) where (val, signedExact) = objectToSignedExactF (wrap . signatureFunction) object@@ -102,70 +118,91 @@ -- | A generalization of 'objectToSignedExact' where the signature function -- runs in an arbitrary functor. This allows for example to sign using an -- algorithm needing random values.-objectToSignedExactF :: (Functor f, Show a, Eq a, ASN1Object a)- => (ByteString -> f (ByteString, SignatureALG)) -- ^ signature function- -> a -- ^ object to sign- -> f (SignedExact a)+objectToSignedExactF+ :: (Functor f, Show a, Eq a, ASN1Object a)+ => (ByteString -> f (ByteString, SignatureALG))+ -- ^ signature function+ -> a+ -- ^ object to sign+ -> f (SignedExact a) objectToSignedExactF signatureFunction object = fmap buildSignedExact (signatureFunction objRaw)- where buildSignedExact (sigBits,sigAlg) =- let signed = Signed { signedObject = object- , signedAlg = sigAlg- , signedSignature = sigBits- }- signedRaw = encodeASN1' DER signedASN1- signedASN1 = Start Sequence- : objASN1- (toASN1 sigAlg- (BitString (toBitArray sigBits 0)- : End Sequence- : []))- in SignedExact signed objRaw signedRaw- objASN1 = \xs -> Start Sequence : toASN1 object (End Sequence : xs)- objRaw = encodeASN1' DER (objASN1 [])+ where+ buildSignedExact (sigBits, sigAlg) =+ let signed =+ Signed+ { signedObject = object+ , signedAlg = sigAlg+ , signedSignature = sigBits+ }+ signedRaw = encodeASN1' DER signedASN1+ signedASN1 =+ Start Sequence+ : objASN1+ ( toASN1+ sigAlg+ ( BitString (toBitArray sigBits 0)+ : End Sequence+ : []+ )+ )+ in SignedExact signed objRaw signedRaw+ objASN1 = \xs -> Start Sequence : toASN1 object (End Sequence : xs)+ objRaw = encodeASN1' DER (objASN1 []) -- | Transform an object into a 'Signed' object. -- -- It's recommended to use the SignedExact object instead of Signed.-objectToSigned :: (Show a, Eq a, ASN1Object a)- => (ByteString- -> (ByteString, SignatureALG, r))- -> a- -> (Signed a, r)+objectToSigned+ :: (Show a, Eq a, ASN1Object a)+ => ( ByteString+ -> (ByteString, SignatureALG, r)+ )+ -> a+ -> (Signed a, r) objectToSigned signatureFunction object = first getSigned $ objectToSignedExact signatureFunction object -- | Try to parse a bytestring that use the typical X509 signed structure format-decodeSignedObject :: (Show a, Eq a, ASN1Object a)- => ByteString- -> Either String (SignedExact a)-decodeSignedObject b = either (Left . show) parseSigned $ decodeASN1Repr' BER b- where -- the following implementation is very inefficient.- -- uses reverse and containing, move to a better solution eventually- parseSigned l = onContainer (fst $ getConstructedEndRepr l) $ \l2 ->- let (objRepr,rem1) = getConstructedEndRepr l2- (sigAlgSeq,rem2) = getConstructedEndRepr rem1- (sigSeq,_) = getConstructedEndRepr rem2- obj = onContainer objRepr (either Left Right . fromASN1 . map fst)+decodeSignedObject+ :: (Show a, Eq a, ASN1Object a)+ => ByteString+ -> Either String (SignedExact a)+decodeSignedObject b = either Left parseSigned $ safeDecode $ decodeASN1Repr' BER b+ where+ -- the following implementation is very inefficient.+ -- uses reverse and containing, move to a better solution eventually+ parseSigned l = case getConstructedEndRepr l of+ (outer, []) -> onSequence outer $ \l2 ->+ let (objRepr, rem1) = getConstructedEndRepr l2+ (sigAlgSeq, rem2) = getConstructedEndRepr rem1+ (sigSeq, rem3) = getConstructedEndRepr rem2+ obj = onSequence objRepr (fromASN1 . map fst) in case (obj, map fst sigSeq) of- (Right (o,[]), [BitString signature]) ->+ _ | not (null rem3) -> Left "signed object error: trailing data"+ (Right (o, []), [BitString signature]) -> let rawObj = Raw.toByteString $ concatMap snd objRepr in case fromASN1 $ map fst sigAlgSeq of- Left s -> Left ("signed object error sigalg: " ++ s)- Right (sigAlg,_) ->- let signed = Signed- { signedObject = o- , signedAlg = sigAlg- , signedSignature = bitArrayGetData signature- }- in Right $ SignedExact- { getSigned = signed- , exactObjectRaw = rawObj+ Left err -> Left ("signed object error sigalg: " ++ err)+ Right (sigAlg, []) ->+ let signed =+ Signed+ { signedObject = o+ , signedAlg = sigAlg+ , signedSignature = bitArrayGetData signature+ }+ in Right $+ SignedExact+ { getSigned = signed+ , exactObjectRaw = rawObj , encodeSignedObject = b }- (Right (_,remObj), _) ->+ Right _ -> Left "signed object error sigalg: trailing data"+ (Right (_, []), _) -> Left "signed object error: invalid signature"+ (Right (_, remObj), _) -> Left $ ("signed object error: remaining stream in object: " ++ show remObj)- (Left err, _) -> Left $ ("signed object error: " ++ show err)- onContainer ((Start _, _) : l) f =- case reverse l of- ((End _, _) : l2) -> f $ reverse l2- _ -> f []- onContainer _ f = f []+ (Left err, _) -> Left $ ("signed object error: " ++ err)+ _ -> Left "signed object error: trailing data"+ onSequence ((Start Sequence, _) : l) f =+ case reverse l of+ ((End Sequence, _) : l2) -> f $ reverse l2+ _ -> Left "signed object error: invalid sequence"+ onSequence _ _ = Left "signed object error: expecting a sequence"
Setup.hs view
@@ -1,2 +1,3 @@ import Distribution.Simple+ main = defaultMain
+ Tests/MLDSAKeys.hs view
@@ -0,0 +1,365 @@+-- | ML-DSA private keys in PKCS#8, as OpenSSL 3.6.4 writes them.+--+-- Not generated here: the point of these is that another implementation+-- made them. A round trip through this library's own encoder and decoder+-- says only that the two halves agree; these say that what comes out is+-- what the rest of the world reads.+--+-- openssl genpkey -algorithm ML-DSA-44 | openssl pkey -outform DER+--+-- OpenSSL writes the @both@ form of RFC 9881 section 6: the seed and the+-- expanded key in a SEQUENCE.+module MLDSAKeys (+ opensslMLDSA44,+ opensslMLDSA65,+ opensslMLDSA87,+) 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++-- | 2626 bytes of DER.+opensslMLDSA44 :: BS.ByteString+opensslMLDSA44 = hex $ concat+ [ "30820a3e020100300b060960864801650304031104820a2a30820a260420151dff249cb3"+ , "4b87169de5d99e2b19666f2a9efbecab731295509007c22ddcc604820a003053ed09fbcf"+ , "1d28675cc66c20e7bb04cb7e077b11f285aec9ce9ae530526ab0299ad6d0887cff9a40ff"+ , "d31ea92f2b7ef42338fe02d3159b236d1252012e65a60936c589b63435a8f2f65b5b6f16"+ , "058f72851d5e63f064187083aafbec42927db7b13528591a2336c476736e0c0a0c6dacb7"+ , "6c70949268a84b9530bb2bb2689608a72c48982044c01014a721d224644b820914876cd9"+ , "40090386418440221ba26ccc42818816608230420ba684d9b40921236959182d084852d8"+ , "380c04367102254e82b21021c78c4b442e123071822621184720c8226298120adb207118"+ , "248ae40084e2b4315ac220e0404089900023119201c628123351db10848bc88808382c0c"+ , "498c81360441380cc32012180460c2c844d0384144102909448ad2382592442a1929721a"+ , "2388d1328d51a68c21460e1811510ca3459a9608d0c824a4c87003b9840a284462b84d08"+ , "99501c803020b890c1b0654a20012403441146665430868b48910a448d4ca80801994d9a"+ , "847161288664248999427009c825609441a4948042200401046c2202311ca184a0002dc4"+ , "c24c51088898a6699aa2298b106d44448e1129721b000a93b229da1249cc164022182d91"+ , "26442014004c4866002461c1b0059a140c02238a1b410e0a3806cb9251524840cc80290b"+ , "04224218686440828c964852445209906162a27181066a5ab48c20984d893805cbc84881"+ , "8090d4a2915006651326649aa608e2c8059128041a27729c228853b86541382e89b23001"+ , "828d1b820022115159a41024436498a0508a06648c020093c6411b060e932021d0004021"+ , "21801c364609292198c2659c3449d8126a0811452246218c864ca0260c9c023199880c22"+ , "2149e39809d2342501a570d4a83150c0601c929082a60d02c629d0400a44068404b9611a"+ , "866003396d0a186463c0680820204b260a114992a30049099089044752a3186610298d8a"+ , "446682320850b2904ac289d9122d44462212246193a62804a28854a80c00b74c51044403"+ , "801012458e50162cd3285002c4051c388ca04412903070a1c861cc349080c42c43324224"+ , "45269c96696288688c268299b26c4c823000b2809c24051ab889530685028401d3c0491a"+ , "80680003861b252c523669d3c62019042453222983866d9102826496910a4321da462493"+ , "404ad23689233031a1104a01328108396880288d608271440404d81865d2a0818c44095c"+ , "a08d43188401c971101205c8c0045b1085dc2050cac410a320319a35cb74122d502593d4"+ , "edf07f9236080bd29e26691f48721d4724b5a1b13a14aae5f8a1d1e0504419ac39dea10a"+ , "5ad354bba5a81c391739a3505d5e92d3b35ad7a74c64b0c46229a61be43cfb9e14aa97ab"+ , "99295cf2212be68590e7e53659f2cb6a5718a0859acd609fd94845ddee0927c75547d1d4"+ , "ab9864f60266df48f9afae8ee8275f98c8273f6be0249e6f0c069da46d215596cbc1c5d2"+ , "ce17c67287e7696e45a6d9fea29ef1a7206855d87841a929837277f7aa0ef8118e52659e"+ , "a033c42ef06cbc913fb02ceeea3a1bc9d5c09e89d8dc49d85044a01e8803fe3a540b02f3"+ , "ec78fcf2611c103a8f9b5bd9db91b9a69a12b96402cc6866b16fd22923ce78e8c75754a3"+ , "6c04aa80b21f0a90c28ee2e6e567be4a278427619965e289dde9643fe4b483fa70367efb"+ , "9d52a517a2b1798dab0a4e89198cc3fd30afcd85ee423523f06cb23c7959c0d120256561"+ , "88c4a818e7fec6e7195cf3a5ad016f93d8a62cd6b557cc6400ed2e81b43613f0da80934d"+ , "d9be78bfdacd6fe50819498a076806a326fb3825dfff67a8dbf2da4cd81b88965d8b170e"+ , "87e56a796c028e6511ca9a3db4eefadc1a0d57d75e1d75ebefeffe9ac4d0ec5a60cad8ae"+ , "27e6f39afda951b2de41e4042845584e753654a619f1c9df5c7996ddde570ff42522538a"+ , "5e323936f2b3bced1eadffc5bcef84d16b729a8a9442ac7c3844b66dbc75deb4904bc207"+ , "948f162bbfbea6f8b7788f90cd66b61120b8c29b317cead830d018d6990b9bcfa6c907bd"+ , "8ea63176fa89bf0c4af60f28b4604bff034a36f70be8ed8d004ef520f292cc8e9202c0fb"+ , "28df92c04296547f3ab012068fd24cce21307201ade6b7b7071937471be57ef02173e7c0"+ , "fddcc302c210f3ba2defd3631b174a590371e81dc4a0c8a7c79ce59840d4fb1b2620ac11"+ , "c831b43da3525db213adbe3b35295aef04bed771db85cee59ce7a8ede9bf1782ed0b074f"+ , "c3db5bcc5b6d101e250df37913d3b76babc9ff7852fe9f47427d04ee0c19ed869297428c"+ , "84e0549e6fdbf16733fa32097dfd97ff5165c9dd34e6db794de6d9680e995fef0c22a3cc"+ , "28cf4fdb3b080269d7f1aa65516042186ad420a75841d7c762f0e4754113aa518d185d6a"+ , "934704b285d78fec4d34246c338e062687cc0f1f9311e948428ee7885492fd0c08da6471"+ , "d3a2afd3e7388989ceb0e91f905d1e0f6e2f67c2be69dbb6df0f421ca8403f69946e88fe"+ , "b695b0b1b6cd93a25a8316527505dbad480a59bce5b68d261851311ad410efd9ccb10ee5"+ , "0f8448d1493242050e016912f80789c15ea5bbf382600203360deec68ac3ccdd861c54b2"+ , "8555a398ef400792e6410f37aa74a502ecee6130da2f8b2a97005f76386978c1300e4e50"+ , "49a722a0af7de32b010a73a6514a614dc80901fa868ab749ed109ee5d10a3807e2b3b4d8"+ , "a5bbaa4b6d3f88104798135ecf77ddb314f7bfdc0a1eb461bc3a1890dea5e62ce4a1cdb0"+ , "411b585178bb6fedd29a56b1cabdc93d09e008199a6558742bf8d66899ea6f10aab34bb2"+ , "f6b08dddbba4169f6f61a7c5368addb74b6c4b8dbc9882abddbdcc403b749f5edd4a3b70"+ , "561a44b34c3f85ef84c845751e983025e50d984eaf38a0d470d73436a537ce1f07666751"+ , "8fcd15547d98e79f27c6241da5fdba9946a3916e2037f76ce82535a17a1618a8894e63a5"+ , "1fb2258a2e5e7794ad9e839cc03c3a2113204b514ac55e4e9e330b2295c65504eb16714d"+ , "af385fa09b3dc92a2594c75fada27a17cc09f6d5581b08a03136d1ddc4cd2bfe1f7c384a"+ , "9b01f26698bc0e3914448a6ce6f50ee09f618b6ee4b29694919cf1c1304c35c9fc429964"+ , "31f1c5e1965383bdd9d6e85a1df1f6a73065a1cc4dc00ae7e69bff0683d844c5bfdcdc08"+ , "05dcd36ffbcdd7bb94fe4194c715197401c97771cccf078d591cea169b25cb60e7148678"+ , "e4efb857bb101a78abb396a73fb8556fba6b265f7dc4c793cf58048a005be22917e61bf8"+ , "edb95cf1005c3a9b6c797f49f25dc13c869399091bcaa0e699cb8258e4b2c843da6a1048"+ , "48e4471eb1e8f08c7482c7531b30174cb433cac5050399fa607bc6244400cf0744caee56"+ , "31ac9a5ecf67abf77c6bfd438fb76f3d18d859b7e209c88e1e5fdeb77bfe999547a207c9"+ , "05e8889fa622043f2b8da2e052e5a160bb006bf40f69761820435c59585d49101607b046"+ , "291f407f795e7d71f5a43eafc36b319a03162a155a40799a61225efe3990aefa4779283d"+ , "ae2b66daa98b28ce95d0a0afcab2e42301f46eec233439e80391941904881e716c4f2c79"+ , "23711d2927e181193a6de8d4329ad358817ddb2463148c3ab985c19808aed1909cce"+ ]++-- | 4098 bytes of DER.+opensslMLDSA65 :: BS.ByteString+opensslMLDSA65 = hex $ concat+ [ "30820ffe020100300b060960864801650304031204820fea30820fe6042062c8740c6f5b"+ , "e0c726ecb2e8c6f1b22faf29ee7a562de1a95a6ace4993812c8e04820fc01a31edba22f1"+ , "50ee1738e8bf87429343d274b5bd69e60feda1dae7b881afd0354992fd2ba1a609acf0b4"+ , "4a0413a86ac8dca104cc460d7cd80db0f38c76ad816f8c692ec5b5c821aa21ded5f1e7b1"+ , "7a8ad3534d2850d1d3f08562ab2b8b00a18f8e796ecc8f9f6d44d19099aa49410fb23e37"+ , "981740d02d957bdd8dd19aa9463e52208184643106838414406247510502717570630322"+ , "333340348846565153734381027643367848711037342000305418167076011152763614"+ , "360036114818757772181646230261447105735122373755001016732454770100313157"+ , "017817783853214666474073350114481534144318477611815667075522034524034561"+ , "405058475248684860680411802753833017174355888413426888852426871532668712"+ , "111433846561762118875606253783552072354337335766843377042210322266862033"+ , "318347136247651233866617100468638340638002367511352001360712375002063667"+ , "513007528247530118344227327731070538433300147277812580606457801432336627"+ , "354041166152518730060160020748471117175588272420573372562508520727654411"+ , "207507452018363433575624541814133431773421663310458463112367254078641742"+ , "601601041567835052631717551465400580807676334023431865516435865273080275"+ , "105305862184715168400303265533644671604143424001288640550704174028060502"+ , "655158646531448117777064104154583325006466524860733405334611440438553060"+ , "561536627177465858121558620423860053888746373827387753536775632241028626"+ , "833887013814141312321545831375434468161657485845108015474443283753833717"+ , "753678738561138255737381602451863450022408252128406317347455344310081565"+ , "526811015763376527042614842148148805104082500020533740381561618131672237"+ , "806557607168670118153081638474686850760447381012211060418005871108243667"+ , "672823514026365327021815127654068432345354144202635848086606318504201076"+ , "347262054208141460281457238134715587066020113468581226120277165763646706"+ , "335268040647817457330735125026055883341578536181455620235405883043100185"+ , "836410080502321606151075828705654646467866335740352251484250636375724436"+ , "700476701341487842804788605677123552714662132871600465871663678172122308"+ , "117801578082508863160152568880765846330011510607645371033231548620270651"+ , "217822156271604815603740340311422686316862400374766762631221508365438245"+ , "322565585663385524478706630016782647387350068870323363054176624783638712"+ , "504004872703415740422242376674302301424417033455127724488012872205680268"+ , "074052636611562483800502260316637482200001108624572715700743752306022188"+ , "440684881514010455750377217655046186824282620128031056600471876815022773"+ , "465323471601830471086315511081723030757186532733414771668757146585873778"+ , "643523825637838431777263531448504444788253215812408468467773328233352487"+ , "470808848157886003582420058711663641226827647106518037834311220647336226"+ , "172235777106242832861510073285581843682263331052140236102155032852815016"+ , "601700412573263188186253846627461715416718320841166781368781674771073677"+ , "453304358813321407060576436306848150507710618286640354123320525147476718"+ , "177333846174371781255824717212823625567200001848525323737344106125680584"+ , "181846483106031726074672420026727441500182257456024485874381257168246807"+ , "585557261283143712318526341803073887550140836151518677231230288877371567"+ , "642718063771662662581227147768585853432257306476775841358601510038120126"+ , "407387663325055740436215754707688310d0d58aa8cc178e2462327d7adbbc0a8bd863"+ , "62d4c35db9d95f18842c38d2f408451e1f4f971623d954df6e0fa9a4595de7984746f11c"+ , "8b09de3bd6d2cc60788f319552e0e0364b1d5a3cce106c495bf349bcdb51000dec34590b"+ , "f11bcc1dcda4f2bf50efe394d62f846822fa3a96126974be047e456c7bb0a1124b448332"+ , "fcbd5865a1ef81be8838075bc129eca0c7dedc9a2736da6391124d1da59014391b35c625"+ , "74c66b96235ec17ad7ff4f7974d20d10a2ad9d7613c91e7785ef955f8d289baed537046b"+ , "90a18fd35058f6efbdf996625824f0f2b6da5449a64ec8c17155a152c5736f5185be3bf2"+ , "ece2ebb06947a0f39a12bd704b097b04291ae4af4ebdbe087a6a17cb1520c869f62ab927"+ , "99a6d2d798ef01978f6d00eeee529b28992d54aa47a64c99feca55ffcd52eb7c84a7fc19"+ , "3899a23b8a639d5f682e0bbf16cb12f609506866565fec091ee97001335a4252065447ec"+ , "81e734d2f911d0ac496fe94b40b7beb5b52d6f5949f5ade53b3aaa8d9ee35e7c7b6a5f80"+ , "f010b69e1f1d781c0f7dd730106b2dc17c9f9cfb64003acfca0013968d98d865f5a1d253"+ , "fbf78d7fc30f7bde65212f4aabfc3e976178ed6f94d12b084b3aa2031e4aeeabc2fb691e"+ , "9dbe40c2d7a32a92d86dab00c39c8bbf94b93f20c68ff711250ce43ad169c228133b0958"+ , "97c62cbe2706dad8cf23f2ed1ddca4200d6ce9fcb7c48ae6dd080316cfbe87d36a3a9a80"+ , "04caa374b0f08e9e0faadf53cd0130c0116aefa222ab2d2a7c8c7d5ab3e17e8a7d0a98dc"+ , "818331657ffb452e65e110b63ba008a6c1250a1198e11855078c1c76c3777dbd3da08160"+ , "78977b9873b9537da023466a3ccd47520bc3254224b583932259bfcf6df1cf9cae1bbde9"+ , "814c4bc05da3385d18af20e91dacebc9827cfb5c342205e49dbd3110af4c5ad0c9b3c435"+ , "945e9152929bb094444101dfc95c9847bec5721b0a629b2f1ef646c6eba796d4409fa889"+ , "240e127e9b530070dc78e504160aa8a7e01483c48d54925ae36ee91f6c1647c0c292522b"+ , "931ecc6544c1e1ef933205cc4665d7c43a5e537df9de1ce34b9eb985ab9abe607228a748"+ , "0f96f7f2c233feb9d3039980cf8c9aec54f92ec8211a9a2d7ad42eaa9c0da5e7d032e63d"+ , "d1c85cbc732c90f07e1411086c95f401a68da033db92a1144c09ada62e6022443b0ee70b"+ , "8ca04c4fe663c304449fcf4236b9cac8461d5ae3e3ccc409afc5f0aa4d02abe980995545"+ , "1198f88d143488f62d5ec2f5301f706a19efebda7878a6e1afa7daafcac0d45fb8451ea5"+ , "6c681937f0ccec0c1b3a437e12bdcbcb62a17ad1d99f499b8b9c1bb35e85dfb88bdccd91"+ , "f71e1bfba790a5200c166aedc29b7fed78b1e4a0691229f2e8add8377e369005867b1e5d"+ , "c43050fe546c65751e79ad032323e039e1ac67acc081c1b157771edfad6e275f105460f3"+ , "7da53ac4ea4941490527233925b7f860eebeaf89ef096a4a00979c61e6dc8bbcee482ad6"+ , "822041e8625a69fd6616981240cc2a01ca33bd67a674e273994632a43f141b89a89a24e4"+ , "fa94780b9b3fab34669f6f6acd264b4a0cb8f0f3f7260a784c79efcb9107d6d784ac4a67"+ , "a86f50da3c7cec7783914727dd0d06343d84f9760dd8c3de98eb3b6240277985b14e5baf"+ , "3ce83fb02d7bdd97fbd7aae97a6fd159c0c910f7004de43605dcec069c9e9dd9678b7bc6"+ , "2614217df4ba635ed1636149ac6c207bdb149a551d5b73037cb238f677a113316a857cea"+ , "6763fe1386e59568dd82970e7f006c0b312e49c31047e2af7b52c9964f94fd207fe7773a"+ , "68978dec08cf2cd350b9d1728c663725499e4f98504d8620762d175ac7a061552a65b088"+ , "fcf048b64d94f3e63bb1fb5daae5b8e6b4475fed3a7440406affcbbe1ad9100b50ec1fce"+ , "b5863a77ec8be20c17afa9fec9827d0cf108f945317c9b6aa295fd59ad9127d7455dd18d"+ , "5cae5bf6f821020255e7687f445e205ae71ecdb2511264284f04b6d5f3d30e26a608cfb0"+ , "a60623e1a66d3686344ce160092bf808c95ea6a9bef196a903a4d1482c354945fe88820e"+ , "f13501c270c02864a63134051184449ed9201d49184ff824c5185f82c49bda8cb1a2b051"+ , "163016814fd1bb5fdb2d936bc4f5c21e5ee3e8584179e43be5cde2f2b47c457be9980559"+ , "5bc3e9d8e4c9ce8e748e8cfa9f4ecacd228ddd7690084d0d893ab014bc72e70dad8264f5"+ , "8eb498caa0e3025f43fc71c02dd32afed753b5d8a46dd9c8b3978e8e4163423cfb0dbfec"+ , "a06b3666ab5743afc0d540604755bf716a1de0c6d32c7e28eda63e69053b9e54a4569ce5"+ , "58ed1049f3058efec60877a53b9f56ca3a217a95a3bf918f5d1a58fe2a890ff8f72f1d32"+ , "df30470cc667e504149b04207c13a16428e3f47b6ea1c6f889bd2363be544f91a326724b"+ , "fde2dd3984475c86a8dd5c7b45b5f76e9162959300790167bca61666085216404e140f4d"+ , "0c2787a85c6d2dfc018ab44e0ea0dc00a89eba64bf71a4e57a2266a96d7a39baebcb682b"+ , "c0361ff336ab7d0b440f5f9d320dd5f705e9316c3be45a3ff96f5ea87dc5ce397f3ae7c5"+ , "38188b253ac6df51906637a6ff5c26066f541eea6d63bdd7821451e1c4769216f5e45511"+ , "d99b949610d222135a8d3dfea12f0d704cdd4012882340db36c1e2085ed065b49fc998c6"+ , "bd4955282cc8c450fe8f5dac5fa4b0dd882a378b399b3097b8afab0ab1d2fe2433fda7f5"+ , "542707b50e49744832b3693b44377b8fbc9362367841e85e1ef9d2789617b302f935fc58"+ , "53fc5a6783bd307c2097f612b173d0b3b24fdf2b332ab9827ada091b8cb4243b23490438"+ , "84abf44ab780599d682484a898c89612dfa6e6e128626b23e32fc1c3bbe717cec0141bc7"+ , "379a3ebf1eb072f70e4aabbdc0a7635760cd74eb850c42bc2b9298794963b833c48ca544"+ , "683e512c5a734e713e10274b0ce5adbe15fad996643fa6c075db2fdac2cb4438027c6b5d"+ , "7eb4f2980c1513d92267f90a6ed8e287f6bde9e745712d2ac6de843f56223bb2f5bd35bc"+ , "c9fd83a782d437e0d6094af64255de70cc2240c7bbc57cb4c5ebff8bf288df4b28822306"+ , "02a1cb7a984e5f6923f8c5db79cea441f8a28a559be3c74d5352f00f5ab5ea6c369f94bf"+ , "432b66e7982c078980edef59d757d133033253b1b55066dac7954d2ca53fc42744eeb541"+ , "bcd971a1ebf832e2925177024222c3eeaa9226efe93e229d1561ff7ed471fc71fb435028"+ , "458438e20d671d26bf3fd1052a255a63b249d855c98f44cf1a01f72acb3e1dde713facf3"+ , "8195d7950e0584f98c0145d5e60d275d299a8607af142d12cfc7f1c1e19b5ce917a3062e"+ , "18f15890ef19f923edcf18a6af4e4b1514fe064b10153793acbc23c3ece6fe2e1095e202"+ , "1d92d82cca5b24d517bf9cd848af9813909604dfd4128b349dde403458e55a34ec4b41c8"+ , "97ea9a909515774e0aa757cb863296bc1c017a693bf7e104aabe3458a08f7b897a5b128d"+ , "463b03d52acd6fccafe603aeef466e3d88887533b76a0a33d3cad5ca1ad7"+ ]++-- | 4962 bytes of DER.+opensslMLDSA87 :: BS.ByteString+opensslMLDSA87 = hex $ concat+ [ "3082135e020100300b06096086480165030403130482134a30821346042086aea35731b2"+ , "7bde938f1eac39d757b84e88fddde9f585703952cca3a8f29b53048213204624fcb8e48e"+ , "f22d91bf330fb8378a5d2d89a7c7800d90c8f289209faef4e924f685483fb0f845abe9bc"+ , "130b4e070ca994d1fb925d736ba629eee21d10e126c02eb255fffa131ba3145c485db180"+ , "69c4bf25d5379c789593e78594b4931e02b497f5d16cfcd44ddf8970fc2271115ced6968"+ , "6c8fe8bf8eda96d66aaf309f650f54c885c396490000620929060bc465123632c892450a"+ , "094e8c1446d1a09113345214c488c3c401db20400b1712dc3844610888a0308502c64461"+ , "98619b068919184ce1805089c26c544671e2482840260160480c904001cc94305b269041"+ , "a4214428308922264c266d81284d0c366c62c211cb8630d238514188095b3689921626e2"+ , "388d10308a9c0010632242caa87003a4719022481cc18861c6480b028192960c8b100152"+ , "406adb846c19054624296603b2600ca76511056658c270d080851c98040a25691925290b"+ , "c7010ba051941264d446818aa4500b022e014231cc14229a382a50144111097140426022"+ , "072183b2688c1624c0c865db84216314125c16214022440b124a24829110a20903184e11"+ , "958184a825d19081d802028c18285286499ba024d9c24d8228469ab000e2924409c4818c"+ , "406c50348c9cb848494464403409cc301120c24863980540144a828684db3232d1b83184"+ , "420161c0658900450b208d08c18400c26d11b56053a42843c8091410261b9311c402600b"+ , "91880c24264a462501818cd9028184286ad4288c6204412146845c126413c00420246940"+ , "10610bb020009508d8107241c40d0c280d932485c032414432718a08405ab445da246c21"+ , "2562cc80208332660b1408004652c30061a30231c19451133305c0a20409166cc4408c12"+ , "4788014701999681c8c46d0ca26c4b368ac19829dab48cd3b68c011284c1a27090086cc2"+ , "34640c174e63120aa22266d18061c4262908474e0bc548d3a26d82184494a8049a804d50"+ , "36052016325cc0450b288d4a86695a2000db084e9c22819b380061a8881c1084c4462660"+ , "c028922252a33872e22672c91042d300264b124ad8927119320e1916325404624c0400c3"+ , "844d648045c0800d030668a4988098887011474d232066db2404a48421832664a2085042"+ , "805101250a5ab405c2a2001b2346a44609a00404a0846594462264c26499a08d92120e80"+ , "107000b800a2184593086a53187204087093060ae1a0881010429826468086410b364804"+ , "b020030266d3a42cd93842129781da9480180785648840e1c22ccab60c6038800cc93089"+ , "188901c9650105825b4681a33861990290ca027159c0045c240009870c42302c8332425b"+ , "2845a4189103c83000142c0812491126520a224804c924c11688dac201113046da84684c"+ , "c40ca2086908b510c8b640d32462c2a888a02665d8a42c09450a1b1464d28620c8386259"+ , "c67110041221352823174900b350121841a3484ca0947054006dd43801e39600112542a1"+ , "a66500c8850aa280d99468424686a30028a4c62d24496508130d61280aa0222d4a068610"+ , "348a8b16118aa8241a14609008000a4365a14849182630d9b2201a19800b34245bc46003"+ , "148201315092420421c1811bc205cb06911a3000013370cc0205e1a888030100c1081201"+ , "c92121170413472c8cc0655b162423434689362c542666980205ca868584946d9c288aa0"+ , "1664dc2442e3402c61c205892080a1008601937011106608014dcc186c99868de4406a41"+ , "080209b9711a46311a2081e3c88924a04d1112100a3101d90630830432e28244d8488643"+ , "144e19116641169109248a13c6900b2841cc146cdab229099268d48405d31251e0008ed1"+ , "38601321519a4670d9464a18148218000e18170e200728cb384402356a89a08141246c0c"+ , "1886024881d3a289429220a0188614446560c870c01010dc300ec2a00c0a1231d8384d19"+ , "4670e1920090322910822de1c008d11804a1102da3028981b231231484a1026ca3842d14"+ , "c7080cb68c11050d6124241b190582102e2440221bb1914c948010969193c45142188e23"+ , "431153c4614c42641ca61093b260042344cc249160a664881260ccb4712015419a80114c"+ , "160550902020b05041a02c1417208400464c264119470513860ce09460e20608a012418c"+ , "4260249030c318255b224619b86980240260101223b4315828495144529312264a8444da"+ , "b408e4b28cc0c8104bb861e4c2093b72853beba635de72bc5dffee98638ac0059b01dfa7"+ , "74f4a518039a355770b5c4e4cc09dcf898d3be26f98fa8e5b00baf0608055b66e90fd213"+ , "87a1e2a59d648650b128672779707d37ffae34d9f861a20f797bef2f191688653e789fdb"+ , "4f8ca396678f1ddd97befb8073e30577ee1ae6c879ec67185fe2511a47497613c3697263"+ , "8ead3a46de50376a11a19166adec634986d8a4331a7fdeb98734b6c1f9850619afa0d513"+ , "3409e2ce3b96a63db20b0e32aeb8f61e9ee7668a40f0bc1929b5a1890e347c91716cc3e1"+ , "9e6ab093215634b293d333c21df77e1fb7df0dc5588dcaccc4de79282e60d10c9a04fa16"+ , "3bee28c2275f0eb8d0ee30f4ed06541f57bef39b0808d14ae28c3585b4e538e87aec5ea8"+ , "b6c1fc19160ec3b4ddfc4f018d408bb5e34a5c691aa2b261e2bec96c66854611ff11f94d"+ , "a992c0db558d2d9851a758ea551a6285c8384b6a5790ff07cf4beabb644048b73b8a63ca"+ , "fa50885da407307d676bdfc01840e1513e47aac4306430f5ca946f3f7fa140bb6726138a"+ , "b29fcb3fbf551c6e97c4d63234d0e8a972cc1cd375422f71d8d3b8dc2eaeed51645196e4"+ , "b8c15a469b77b40aabaa3f0b6b6832f4c415fee3f83b9e02e2649879092bc980cdf39f28"+ , "b67b161f0dc49958fd4d32c2484c3a2732ceed9f2073bbd4247027118ead972ae6a74a58"+ , "a25af79ef715bd285f37602fd1a83605c37c0a39f5bf1b618e571eb96aa65c9162521fb6"+ , "79ef1f45bae2e6647c8ae17a3b3e1050004fb92f9f6cf0f178d65d462e59ff839c139262"+ , "1245da9faabbebe93025bf6522679cc84915a5315639f5d1ead92632975be7f29db03b90"+ , "892de9001dcfa7b8fbb7e35cbb3393b76ba88514f60600b9a6a8d0564643ddca1d6f72ad"+ , "c15389debf65bbb72add4fbe2c440ec6f8479d5b1d721feb0f698de826f1bb64ec2fb85a"+ , "61a9db8c6713cbfdedffa4fce1f403511af4765afb56f88a1664fbe5a37a736d9929ade5"+ , "8b192bf96433950f32385d94a4ea501005057dec3511b30996299c61d354712068eea89c"+ , "2ed098b94c7c353b4546ed9fb0637537155cc9abdf345246e20c7e300e13dad32c8d9f2e"+ , "1aba7ae20c8b90ab84e863a835cbf1a00288f6642a3ac050c91eb0987674dfdca68241b6"+ , "e5caf55937d838b5daeeaca88161a48c3951438d33d34814c9f71b0f5f9d657dd0702101"+ , "b1a5a8f708d0b8a3f19a17baa0d63e695e29c6ce78a2b443e023610b81aca48a8fae237b"+ , "0f82b98e69d89943d560c9731e4b395e4e75714ac915b56cb39cfbe9cf5e1d7ab1531883"+ , "21fead83dafddc45b9fa81f0f088bca3fe32684e290d8461e9514797c238262b1dbe42f0"+ , "827a1336273264fcd7ee59147c7e01e896b03b960b96f67cc3ac63f6dc05df6824069e19"+ , "d9518878a7d8b3f1356c452c5d93ffb0f443ed9180b6a7489c119631388f95eca3ce5ab6"+ , "8ffb56ee5cc8b879ac65ba27cd9819ffaa042f23e9ea3d4a1d00b64e73e14645a682c499"+ , "661760b0571f17c94680c30aab8cf3151405cd852621a23354591d4f0aad3d3a481fd634"+ , "b8521c25c3893f1cb7d34524878273bfce2fd45d134e1a78ece266bcfcfc7b043f49c1c3"+ , "916b2ff2848e93921b2b961d93a60fee7b4b34006a1fc5aac978bfb462a27fed57bcdead"+ , "a5864c8ca3e7e45a6cb1ca1af96ff56fe822dccde098ead28ff581a6ec34119dc44b8449"+ , "08ce63260a2fbcd887cc8557fde512c8048f4481452011f13709bf1919961a7a94d99f3c"+ , "e9c8c8311a12a2f6aae242a80af2971fa541999e33e110945a6f46a1e44f551256c8eefa"+ , "fbded8e69f0796b47a14e10e3d5ce65e9b06ef01fe7fa337b8ffcdc9159995bb1f7940bf"+ , "f9b7f06185c904f8bdd629f00db2fc12e5c53cc8cadff9913d755920fa61d3616fbacb90"+ , "d035a637dd5eaa1497efacb87eb2bc7e9fecf449773e925f51635f2a07d6945a8f270ab9"+ , "b1ebdba6228c8c53dfd1446eaaf2cc5a8887f40d91a97d6d9b0e27846185128c762b3981"+ , "a09619c3201b2dd3eafbfdb9a1863a13bfe97116b32dc8784474a1f5395694a0553a72ae"+ , "038afe497755b627632bd90ce3b3b0a15c5249fad5422a93e6cabc26989d6d586e8f935f"+ , "ccf40115b3fcbcda1c0bcb4d1da8eb5d9df47c940b410cb03c10aac83d11a6fe3066f092"+ , "6b3133e214b978f96902f591a159f3668d1c233122da7c3da21ffa9e8cffc556aa63cc7e"+ , "d7202d228fa149acf595261cd3d6f457bdfdb116a1b139ada16e265d417cca161ea4bfae"+ , "c4f2b1e4d2a1a9557a56f4cb36aba114e4d6279e45028fb25f96bc86546a3d351fb99433"+ , "8e9d108d9a5138badd1eb647a74b231871d8b5a994fa56eeb2e09ac04fd89c8f56c157a5"+ , "f9942c75087887098a5c0e959cf72e11bd9008d8eb57ccc4f9513200da7dbb6b3615efe5"+ , "90e619e1ff90c8781e9bf19d2b7b4e04884827d0bd94b297f4a8638575102dd236eca161"+ , "d9771cebd1cc529d85186c84ec86b0376a3ad7745b58af6bacca35b10fed57a349d2fb22"+ , "7b114ca86716a98de8a2aac6b5f678ecd7127e6a09babb182d8fcaff2394d3f65e98a43b"+ , "4d2f58bd29864f0cb0fbae6b6f1b68077f40cfb553c42d873157215e90437f4a648b2c66"+ , "ae049290f717197fb3f00acb82d659281009a0cf9682faa66fdcd2ad7219fb883a236fe9"+ , "3b7768e8df11ca70d094a9faa2c3a87e0293ec1a2feefdda5ea68a53ddced5f12aaa3820"+ , "6fe739d4ef29555dcc720bddcb0e09a757aca320442add161faf36d306682fc89f3aba84"+ , "b07c0a644602bf236f3fbe558e084b90108e3f16171c5bfab6f2e3d2017ef7b476bb3a0d"+ , "ce25e8398ac291259000dc320418d313d5ecba47a1173dfc66aa40a322076ad79c494f48"+ , "b5b2777545fd37cbdf6a295b0bd55982385e38dd4411cc560acc819a4a7e344befe841a0"+ , "964e84e15a517127fba2325e67223b42a308ef43e0a503cf850663a3986abea5b3ed9235"+ , "231ce6988f83c24fb0156a881f5380fb7aefbd6e8fcbb0cd192a80342ec8b5b1748d38fd"+ , "d62d2275594ac48a7dc4c1069a3663f33e10ec711e5d92506cf1e45f3fe21ace45ed80d5"+ , "c3221141a7308b3ea68263665c54d0cee1d36a49bb35595d0720e78b9b8f4e7f94f99947"+ , "219f8d222e0bcc9198bda51b569d70dd26e278b8c3606694c8e06539b6fdd1bef69ea854"+ , "647041ec4035f77bf13748f90ac6ca018f50af5511fd60f43d40ff0314310be5cfcba12b"+ , "c1fe793e66a5954ef7a7a5e1d5699042e96a3f61d026b35b376dd3f494325bcc3dad2571"+ , "5e40d5b9417a2d9c77b247200901a4b489aad5ab83d89f74da9e88e443d557536fb6c452"+ , "af978e477a87f0bcc8cfc0535a6023d7f92826e5ee1f75e6c81bff20d277555e03d7991b"+ , "3b3924023c33b5f80693bbbc33803a7a26206c654b05f6a39974dfe49b579b44a5f6706b"+ , "4841098b9bcaa215865faf270ff186e1208c4614d1217978f07574d85d2a506ae7f77763"+ , "b9e7419d00c8cee5688f14dd154ec9e7e3975f2119d0e9e64b071a6b80e8cf2c1b233317"+ , "d3a64e8caf73cea3b47f2e1102871d40851230e8f09e908fe86495f69fae0a5301b5b289"+ , "8167960fba4c1de5657ede5c958f3adcec887c9f21dfb25ff58edc283a28fb7f2e84fc2a"+ , "1ca28a4602baf26a71d2eaa5b7c2d5f4573d3329f4ed754893700f6e2379b97bb119de85"+ , "f3bc0367f0a23d31c4b7fc01c93574ffad9ea310d40b747fa12cda69e8da8a57ab09a703"+ , "33e76c02abeb43f92c9b118bf234fb33b2dc82f909fbb07250db23dde3dbc14a799b5fbf"+ , "4d5d2c361c8c21871c958117c1bc76d283c80156ab418848b8c189fc93ece61472e34109"+ , "231c2d888f785510f9b9310c49664bb206a548c8b54fb29bf75fc642ab200c1f6fc07ead"+ , "999fa61bc18ad5daba0e299658dde9865b51e54ff4cfe6cf26b5165884053c0ca7c6ff0d"+ , "0774f623ec012f9ec999e2a9b4e24bc854fa89100e07399e24a22c99945e8f1c1de485e5"+ , "43ee1e4f5f095f91d877d1f456c633f5ab5003ffbcea595827d88263ed67c6dc5f5a1aa4"+ , "0b5150c8f6cb4e336cf7ec2a69937fb9d5e1d56e901d608dc6d29c23e27959813fd678fa"+ , "957806dd510c3f69f8aca976178fe08a3e073272337bd1046885320c811d1e2d6d41d170"+ , "0a4cf6773c2cd62d0d5199ed928277a54eca08a42e9037be611d6e7344570db3cb0d82a0"+ , "d166e1162ea3d1b2d32ad10d90f542b8fa2dd9667c7ba465b7b66cda42d34acf612f7049"+ , "d6c720bb613fcffa6c749275c4326dca1a3c95c98ef3ebd79c2625e9b437e52a737a9c05"+ , "c5402a7ebcb81c71b7f9dff761ff3637a353969ce041397afe201cb5d4e519773b4fb9ab"+ , "5389cd6c43f57f7ddd0ce00e9150d31594b4d4584ed4c4f41d0990ec224bb825ff14046f"+ , "6d854347067607eb6740d578694c4542798bcff502517265b8173b0cd8200ae502321695"+ , "9cc405d2bab2ecd22dfa6a967edb6e84377ee2558177148a28bb7d07c85466ea4ddea4e1"+ , "49c0900217737ef402ca9580325c48e73a1a9c2cd62a6dea57489f0cb8399cd3e4a600a8"+ , "210b80de90e38c6c58d9e67b22788939bf01881afa9d325853a1ec6b783d5ce3bab56ac8"+ , "c967b451ece8e2f611faa073ce978344662d001714b493e7bd23937f5ebba2b3bc873931"+ , "e2f8d27fd01071f0b7cd32980f3438423c86ce2bd56d45665029ee7f3097"+ ]
+ 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
@@ -1,223 +1,1359 @@ {-# LANGUAGE ScopedTypeVariables #-}-module Main where--import Test.Tasty-import Test.Tasty.QuickCheck--import qualified Data.ByteString as B--import Control.Applicative-import Control.Monad--import Data.List (nub, sort)-import Data.ASN1.Types-import Data.X509-import Crypto.Error (throwCryptoError)-import qualified Crypto.PubKey.Curve25519 as X25519-import qualified Crypto.PubKey.Curve448 as X448-import qualified Crypto.PubKey.Ed25519 as Ed25519-import qualified Crypto.PubKey.Ed448 as Ed448-import qualified Crypto.PubKey.RSA as RSA-import qualified Crypto.PubKey.DSA as DSA--import Data.Hourglass--instance Arbitrary RSA.PublicKey where- arbitrary = do- bytes <- elements [64,128,256]- e <- elements [0x3,0x10001]- n <- choose (2^(8*(bytes-1)),2^(8*bytes))- return $ RSA.PublicKey { RSA.public_size = bytes- , RSA.public_n = n- , RSA.public_e = e- }--instance Arbitrary DSA.Params where- arbitrary = DSA.Params <$> arbitrary <*> arbitrary <*> arbitrary--instance Arbitrary DSA.PublicKey where- arbitrary = DSA.PublicKey <$> arbitrary <*> arbitrary--instance Arbitrary X25519.PublicKey where- arbitrary = X25519.toPublic <$> arbitrary--instance Arbitrary X448.PublicKey where- arbitrary = X448.toPublic <$> arbitrary--instance Arbitrary Ed25519.PublicKey where- arbitrary = Ed25519.toPublic <$> arbitrary--instance Arbitrary Ed448.PublicKey where- arbitrary = Ed448.toPublic <$> arbitrary--instance Arbitrary PubKey where- arbitrary = oneof- [ PubKeyRSA <$> arbitrary- , PubKeyDSA <$> arbitrary- --, PubKeyECDSA ECDSA_Hash_SHA384 <$> (B.pack <$> replicateM 384 arbitrary)- , PubKeyX25519 <$> arbitrary- , PubKeyX448 <$> arbitrary- , PubKeyEd25519 <$> arbitrary- , PubKeyEd448 <$> arbitrary- ]--instance Arbitrary RSA.PrivateKey where- arbitrary = RSA.PrivateKey <$> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary--instance Arbitrary DSA.PrivateKey where- arbitrary = DSA.PrivateKey <$> arbitrary <*> arbitrary--instance Arbitrary X25519.SecretKey where- arbitrary = throwCryptoError . X25519.secretKey <$> arbitraryBS 32 32--instance Arbitrary X448.SecretKey where- arbitrary = throwCryptoError . X448.secretKey <$> arbitraryBS 56 56--instance Arbitrary Ed25519.SecretKey where- arbitrary = throwCryptoError . Ed25519.secretKey <$> arbitraryBS 32 32--instance Arbitrary Ed448.SecretKey where- arbitrary = throwCryptoError . Ed448.secretKey <$> arbitraryBS 57 57--instance Arbitrary PrivKey where- arbitrary = oneof- [ PrivKeyRSA <$> arbitrary- , PrivKeyDSA <$> arbitrary- --, PrivKeyECDSA ECDSA_Hash_SHA384 <$> (B.pack <$> replicateM 384 arbitrary)- , PrivKeyX25519 <$> arbitrary- , PrivKeyX448 <$> arbitrary- , PrivKeyEd25519 <$> arbitrary- , PrivKeyEd448 <$> arbitrary- ]--instance Arbitrary HashALG where- arbitrary = elements [HashMD2,HashMD5,HashSHA1,HashSHA224,HashSHA256,HashSHA384,HashSHA512]--instance Arbitrary PubKeyALG where- arbitrary = elements [PubKeyALG_RSA,PubKeyALG_DSA,PubKeyALG_EC,PubKeyALG_DH]--instance Arbitrary SignatureALG where- -- unfortunately as the encoding of this is a single OID as opposed to two OID,- -- the testing need to limit itself to Signature ALG that has been defined in the OID database. - -- arbitrary = SignatureALG <$> arbitrary <*> arbitrary- arbitrary = elements- [ SignatureALG HashSHA1 PubKeyALG_RSA- , SignatureALG HashMD5 PubKeyALG_RSA- , SignatureALG HashMD2 PubKeyALG_RSA- , SignatureALG HashSHA256 PubKeyALG_RSA- , SignatureALG HashSHA384 PubKeyALG_RSA- , SignatureALG HashSHA512 PubKeyALG_RSA- , SignatureALG HashSHA224 PubKeyALG_RSA- , SignatureALG HashSHA1 PubKeyALG_DSA- , SignatureALG HashSHA224 PubKeyALG_DSA- , SignatureALG HashSHA256 PubKeyALG_DSA- , SignatureALG HashSHA224 PubKeyALG_EC- , SignatureALG HashSHA256 PubKeyALG_EC- , SignatureALG HashSHA384 PubKeyALG_EC- , SignatureALG HashSHA512 PubKeyALG_EC- , SignatureALG_IntrinsicHash PubKeyALG_Ed25519- , SignatureALG_IntrinsicHash PubKeyALG_Ed448- ]--arbitraryBS r1 r2 = choose (r1,r2) >>= \l -> (B.pack <$> replicateM l arbitrary)--instance Arbitrary ASN1StringEncoding where- arbitrary = elements [IA5,UTF8]--instance Arbitrary ASN1CharacterString where- arbitrary = ASN1CharacterString <$> arbitrary <*> arbitraryBS 2 36--instance Arbitrary DistinguishedName where- arbitrary = DistinguishedName <$> (choose (1,5) >>= \l -> replicateM l arbitraryDE)- where arbitraryDE = (,) <$> arbitrary <*> arbitrary--instance Arbitrary DateTime where- arbitrary = timeConvert <$> (arbitrary :: Gen Elapsed)-instance Arbitrary Elapsed where- arbitrary = Elapsed . Seconds <$> (choose (1, 100000000))--instance Arbitrary Extensions where- arbitrary = Extensions <$> oneof- [ pure Nothing- , Just <$> (listOf1 $ oneof- [ extensionEncode <$> arbitrary <*> (arbitrary :: Gen ExtKeyUsage)- ]- )- ]--instance Arbitrary ExtKeyUsageFlag where- arbitrary = elements $ enumFrom KeyUsage_digitalSignature-instance Arbitrary ExtKeyUsage where- arbitrary = ExtKeyUsage . sort . nub <$> listOf1 arbitrary--instance Arbitrary ExtKeyUsagePurpose where- arbitrary = elements [ KeyUsagePurpose_ServerAuth- , KeyUsagePurpose_ClientAuth- , KeyUsagePurpose_CodeSigning- , KeyUsagePurpose_EmailProtection- , KeyUsagePurpose_TimeStamping- , KeyUsagePurpose_OCSPSigning ]-instance Arbitrary ExtExtendedKeyUsage where- arbitrary = ExtExtendedKeyUsage . nub <$> listOf1 arbitrary--instance Arbitrary Certificate where- arbitrary = Certificate <$> pure 2- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary--instance Arbitrary RevokedCertificate where- arbitrary = RevokedCertificate <$> arbitrary- <*> arbitrary- <*> arbitrary--instance Arbitrary CRL where- arbitrary = CRL <$> pure 1- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary- <*> arbitrary--property_unmarshall_marshall_id :: (Show o, Arbitrary o, ASN1Object o, Eq o) => o -> Bool-property_unmarshall_marshall_id o =- case got of- Right (gotObject, [])- | gotObject == o -> True- | otherwise -> error ("object is different: " ++ show gotObject ++ " expecting " ++ show o)- Right (gotObject, l) -> error ("state remaining: " ++ show l ++ " marshalled: " ++ show oMarshalled ++ " parsed: " ++ show gotObject)- Left e -> error ("parsing failed: " ++ show e ++ " object: " ++ show o ++ " marshalled as: " ++ show oMarshalled)- where got = fromASN1 oMarshalled- oMarshalled = toASN1 o []--property_extension_id :: (Show e, Eq e, Extension e) => e -> Bool-property_extension_id e = case extDecode (extEncode e) of- Left err -> error err- Right v | v == e -> True- | otherwise -> error ("expected " ++ show e ++ " got: " ++ show v)--main = defaultMain $ testGroup "X509"- [ testGroup "marshall"- [ testProperty "pubkey" (property_unmarshall_marshall_id :: PubKey -> Bool)- , testProperty "privkey" (property_unmarshall_marshall_id :: PrivKey -> Bool)- , testProperty "signature alg" (property_unmarshall_marshall_id :: SignatureALG -> Bool)- , testGroup "extension"- [ testProperty "key-usage" (property_extension_id :: ExtKeyUsage -> Bool)- , testProperty "extended-key-usage" (property_extension_id :: ExtExtendedKeyUsage -> Bool)- ]- , testProperty "extensions" (property_unmarshall_marshall_id :: Extensions -> Bool)- , testProperty "certificate" (property_unmarshall_marshall_id :: Certificate -> Bool)- , testProperty "crl" (property_unmarshall_marshall_id :: CRL -> Bool)- ]- ]++module Main where++import Test.Tasty+import Test.Tasty.QuickCheck++import qualified Data.ByteString as B++import Control.Monad++import Crypto.Debug (DebugShow (..))+import Crypto.Error (throwCryptoError)+import Crypto.Number.Serialize (i2ospOf_)+import qualified Crypto.PubKey.Curve25519 as X25519+import qualified Crypto.PubKey.Curve448 as X448+import qualified Crypto.PubKey.DSA as DSA+import qualified Crypto.PubKey.ECC.Prim as ECC+import qualified Crypto.PubKey.ECC.Types as ECC+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)+import Data.ASN1.Encoding (decodeASN1', encodeASN1')+import Data.ASN1.Types+import Data.ByteArray (convert)+import Data.List (isInfixOf, nub, sort)+import Data.Maybe (fromJust)+import Data.Proxy (Proxy (..))+import Data.X509+import Data.X509.EC (ecPubKeyCurveName)++import MLDSAKeys+import MLKEMKeys++import Data.Hourglass++instance Arbitrary RSA.PublicKey where+ arbitrary = do+ bytes <- elements [64, 128, 256]+ e <- elements [0x3, 0x10001]+ n <- choose (2 ^ (8 * (bytes - 1)), 2 ^ (8 * bytes))+ return $+ RSA.PublicKey+ { RSA.public_size = bytes+ , RSA.public_n = n+ , RSA.public_e = e+ }++instance Arbitrary DSA.Params where+ arbitrary = DSA.Params <$> arbitrary <*> arbitrary <*> arbitrary++instance Arbitrary DSA.PublicKey where+ arbitrary = DSA.PublicKey <$> arbitrary <*> arbitrary++instance Arbitrary X25519.PublicKey where+ arbitrary = X25519.toPublic <$> arbitrary++instance Arbitrary X448.PublicKey where+ arbitrary = X448.toPublic <$> arbitrary++instance Arbitrary Ed25519.PublicKey where+ arbitrary = Ed25519.toPublic <$> arbitrary++instance Arbitrary Ed448.PublicKey where+ arbitrary = Ed448.toPublic <$> arbitrary++instance Arbitrary PubKey where+ arbitrary =+ oneof+ [ PubKeyRSA <$> arbitrary+ , PubKeyRSAPSS <$> arbitrary <*> arbitraryKeyPSS+ , PubKeyDSA <$> arbitrary+ , PubKeyDH <$> arbitraryDH+ , -- , PubKeyECDSA ECDSA_Hash_SHA384 <$> (B.pack <$> replicateM 384 arbitrary)+ PubKeyX25519 <$> arbitrary+ , PubKeyX448 <$> arbitrary+ , PubKeyEd25519 <$> arbitrary+ , PubKeyEd448 <$> arbitrary+ , 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+ <$> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary++instance Arbitrary DSA.PrivateKey where+ arbitrary = DSA.PrivateKey <$> arbitrary <*> arbitrary++instance Arbitrary X25519.SecretKey where+ arbitrary = throwCryptoError . X25519.secretKey <$> arbitraryBS 32 32++instance Arbitrary X448.SecretKey where+ arbitrary = throwCryptoError . X448.secretKey <$> arbitraryBS 56 56++instance Arbitrary Ed25519.SecretKey where+ arbitrary = throwCryptoError . Ed25519.secretKey <$> arbitraryBS 32 32++instance Arbitrary Ed448.SecretKey where+ arbitrary = throwCryptoError . Ed448.secretKey <$> arbitraryBS 57 57++instance Arbitrary PrivKey where+ arbitrary =+ oneof+ [ PrivKeyRSA <$> arbitrary+ , PrivKeyRSAPSS <$> arbitrary <*> arbitraryKeyPSS+ , PrivKeyDSA <$> arbitrary+ , -- , PrivKeyECDSA ECDSA_Hash_SHA384 <$> (B.pack <$> replicateM 384 arbitrary)+ PrivKeyX25519 <$> arbitrary+ , PrivKeyX448 <$> arbitrary+ , PrivKeyEd25519 <$> arbitrary+ , PrivKeyEd448 <$> arbitrary+ , 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++-- | All three forms are generated, so that the marshalling round trip+-- 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 [MLKeySeed, MLKeyExpanded, MLKeyBoth]+ throwCryptoError . privkeyMLDSAFromSeed p form <$> arbitraryBS 32 32++instance Arbitrary HashALG where+ arbitrary =+ elements+ [ 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]++instance Arbitrary SignatureALG where+ -- unfortunately as the encoding of this is a single OID as opposed to two OID,+ -- the testing need to limit itself to Signature ALG that has been defined in the OID database.+ -- arbitrary = SignatureALG <$> arbitrary <*> arbitrary+ arbitrary =+ elements+ [ SignatureALG HashSHA1 PubKeyALG_RSA+ , SignatureALG HashMD5 PubKeyALG_RSA+ , SignatureALG HashMD2 PubKeyALG_RSA+ , SignatureALG HashSHA256 PubKeyALG_RSA+ , SignatureALG HashSHA384 PubKeyALG_RSA+ , SignatureALG HashSHA512 PubKeyALG_RSA+ , SignatureALG HashSHA224 PubKeyALG_RSA+ , SignatureALG HashSHA1 PubKeyALG_DSA+ , SignatureALG HashSHA224 PubKeyALG_DSA+ , SignatureALG HashSHA256 PubKeyALG_DSA+ , SignatureALG HashSHA224 PubKeyALG_EC+ , 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+ , SignatureALG_IntrinsicHash PubKeyALG_MLDSA65+ , SignatureALG_IntrinsicHash PubKeyALG_MLDSA87+ ]++arbitraryBS r1 r2 = choose (r1, r2) >>= \l -> (B.pack <$> replicateM l arbitrary)++instance Arbitrary ASN1StringEncoding where+ arbitrary = elements [IA5, UTF8]++instance Arbitrary ASN1CharacterString where+ arbitrary = ASN1CharacterString <$> arbitrary <*> arbitraryBS 2 36++instance Arbitrary DistinguishedName where+ arbitrary = DistinguishedName <$> (choose (1, 5) >>= \l -> replicateM l arbitraryDE)+ where+ arbitraryDE = (,) <$> arbitrary <*> arbitrary++instance Arbitrary DateTime where+ arbitrary = timeConvert <$> (arbitrary :: Gen Elapsed)+instance Arbitrary Elapsed where+ arbitrary = Elapsed . Seconds <$> (choose (1, 100000000))++instance Arbitrary Extensions where+ arbitrary =+ Extensions+ <$> oneof+ [ pure Nothing+ , Just+ -- at most one instance of an extension+ <$> ( (: [])+ <$> (extensionEncode <$> arbitrary <*> (arbitrary :: Gen ExtKeyUsage))+ )+ ]++instance Arbitrary ExtKeyUsageFlag where+ arbitrary = elements $ enumFrom KeyUsage_digitalSignature+instance Arbitrary ExtKeyUsage where+ arbitrary = ExtKeyUsage . sort . nub <$> listOf1 arbitrary++instance Arbitrary ExtKeyUsagePurpose where+ arbitrary =+ elements+ [ KeyUsagePurpose_ServerAuth+ , KeyUsagePurpose_ClientAuth+ , KeyUsagePurpose_CodeSigning+ , KeyUsagePurpose_EmailProtection+ , KeyUsagePurpose_TimeStamping+ , KeyUsagePurpose_OCSPSigning+ ]+instance Arbitrary ExtExtendedKeyUsage where+ arbitrary = ExtExtendedKeyUsage . nub <$> listOf1 arbitrary++instance Arbitrary Certificate where+ arbitrary =+ Certificate+ <$> pure 2+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary++instance Arbitrary RevokedCertificate where+ arbitrary =+ RevokedCertificate+ <$> arbitrary+ <*> arbitrary+ <*> arbitrary++instance Arbitrary CRL where+ arbitrary =+ CRL+ <$> pure 1+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary++property_unmarshall_marshall_id+ :: (Show o, Arbitrary o, ASN1Object o, Eq o) => o -> Bool+property_unmarshall_marshall_id o =+ case got of+ Right (gotObject, [])+ | gotObject == o -> True+ | otherwise ->+ error ("object is different: " ++ show gotObject ++ " expecting " ++ show o)+ Right (gotObject, l) ->+ error+ ( "state remaining: "+ ++ show l+ ++ " marshalled: "+ ++ show oMarshalled+ ++ " parsed: "+ ++ show gotObject+ )+ Left e ->+ error+ ( "parsing failed: "+ ++ show e+ ++ " object: "+ ++ show o+ ++ " marshalled as: "+ ++ show oMarshalled+ )+ where+ got = fromASN1 oMarshalled+ oMarshalled = toASN1 o []++-- | A scalar long enough that finding it in the rendered key cannot be an+-- accident of the curve parameters beside it.+newtype ECSecret = ECSecret Integer+ deriving (Show)++instance Arbitrary ECSecret where+ arbitrary = ECSecret <$> choose (10 ^ (40 :: Int), 10 ^ (41 :: Int))++-- | 'show' of an EC private key holds the curve and not the scalar, and+-- 'debugShow' holds both. The wrapper is checked too, since it is+-- @Credential@ and @ServerParams@ that a program actually prints.+property_ec_show_redacts :: ECSecret -> Bool+property_ec_show_redacts (ECSecret d) = all ok [named, prime]+ where+ named = PrivKeyEC_Named ECC.SEC_p256r1 d+ prime = PrivKeyEC_Prime d 1 2 3 (SerializedPoint B.empty) 4 1 5+ digits = show d+ ok k =+ not (digits `isInfixOf` show k)+ && not (digits `isInfixOf` show (PrivKeyEC k))+ && "<secret>" `isInfixOf` show k+ && digits `isInfixOf` debugShow k+ && digits `isInfixOf` debugShow (PrivKeyEC k)++-- | RFC 9881 Section 6: an ML-DSA-44 private key in PKCS#8 is the seed,+-- tagged [0], the expanded key, or both. All three give one signing key,+-- and each is written back out as what it was read as.+newtype MLDSASeed = MLDSASeed B.ByteString deriving (Show)++instance Arbitrary MLDSASeed where+ arbitrary = MLDSASeed <$> arbitraryBS 32 32++mldsaPKCS8ASN1 :: [ASN1] -> [ASN1]+mldsaPKCS8ASN1 inner =+ [ Start Sequence+ , IntVal 0+ , Start Sequence+ , OID [2, 16, 840, 1, 101, 3, 4, 3, 17]+ , End Sequence+ , OctetString (encodeASN1' DER inner)+ , End Sequence+ ]++mldsaPKCS8 :: [ASN1] -> Either String (PrivKey, [ASN1])+mldsaPKCS8 = fromASN1 . mldsaPKCS8ASN1++mldsaExpanded :: B.ByteString -> B.ByteString+mldsaExpanded seed =+ convert $+ snd $+ throwCryptoError $+ MLDSA.keyPairFromSeed (Proxy :: Proxy MLDSA.MLDSA44) seed++-- | The three encodings of one seed, with the form each of them is.+mldsaForms :: B.ByteString -> [(MLKeyForm, [ASN1])]+mldsaForms seed =+ [ (MLKeySeed, [Other Context 0 seed])+ , (MLKeyExpanded, [OctetString expanded])+ ,+ ( MLKeyBoth+ , [Start Sequence, OctetString seed, OctetString expanded, End Sequence]+ )+ ]+ where+ expanded = mldsaExpanded seed++-- | Each form parses, and all three carry the one signing key the seed+-- expands to. The forms themselves stay apart: the parsed keys are three+-- different values, because they are three different files.+property_mldsa_forms :: MLDSASeed -> Bool+property_mldsa_forms (MLDSASeed seed) =+ map (fmap fst . mldsaPKCS8 . snd) (mldsaForms seed)+ == map (Right . expected) forms+ && length (nub (map expected forms)) == 3+ where+ forms = map fst (mldsaForms seed)+ expected form =+ PrivKeyMLDSA44 $+ throwCryptoError $+ privkeyMLDSAFromSeed (Proxy :: Proxy MLDSA.MLDSA44) form seed++-- | Reading a key and writing it again gives back the bytes it came from,+-- for each of the three forms. This is what keeping the form is for: a+-- key store that rewrites a file must not turn a seed into an expanded key+-- behind the owner's back.+property_mldsa_form_round_trip :: MLDSASeed -> Bool+property_mldsa_form_round_trip (MLDSASeed seed) = all ok (mldsaForms seed)+ where+ ok (form, inner) = case mldsaPKCS8 inner of+ Right (k, []) ->+ toASN1 k [] == mldsaPKCS8ASN1 inner+ && formOf k == Just form+ _ -> False+ formOf (PrivKeyMLDSA44 k) = Just (privkeyMLDSA_form k)+ formOf _ = Nothing++-- | The seed caught at generation, written out and read back.+--+-- This is the whole point of the two halves: @crypton@'s+-- 'MLDSA.generateKeyPairAndSeed' is the only way to keep the seed a key was+-- made from, and the seed form of RFC 9881 Section 6 is where it goes.+-- Nothing else here generates a key, so without this the two never meet.+--+-- The key the seed expands to is the one that was generated, the file reads+-- back as what was written, and the file is shorter than the expanded key+-- alone -- which is what writing the seed is for.+property_mldsa_generated_seed :: Property+property_mldsa_generated_seed = ioProperty $ do+ (_, sk, seed) <- MLDSA.generateKeyPairAndSeed p+ let k = throwCryptoError $ privkeyMLDSAFromSeed p MLKeySeed seed+ privkey = PrivKeyMLDSA44 k+ encoded = toASN1 privkey []+ return $+ privkeyMLDSA_key k == sk+ && fromASN1 encoded == Right (privkey, [])+ && B.length (encodeASN1' DER encoded) < B.length (convert sk :: B.ByteString)+ where+ p = Proxy :: Proxy MLDSA.MLDSA44++-- | What another implementation writes, this one reads and writes back.+--+-- Everything else here encodes with this library and decodes with it again,+-- which says the two halves agree and nothing about the bytes. These keys+-- were made by OpenSSL 3.6.4, so they say what no round trip can: that a+-- PKCS#8 from the rest of the world parses, and that what goes back out is+-- byte for byte what came in.+--+-- OpenSSL writes the @both@ form, which is also the case that has something+-- to check -- the expanded key must be what the seed expands to, or the+-- parse is refused.+property_mldsa_openssl :: Bool+property_mldsa_openssl = all ok keys+ where+ keys =+ [ (opensslMLDSA44, "ML-DSA-44")+ , (opensslMLDSA65, "ML-DSA-65")+ , (opensslMLDSA87, "ML-DSA-87")+ ]+ ok (der, _) = case decodeASN1' DER der of+ Left _ -> False+ Right asn1 -> case fromASN1 asn1 :: Either String (PrivKey, [ASN1]) of+ Right (k, []) ->+ formOf k == Just MLKeyBoth+ && encodeASN1' DER (toASN1 k []) == der+ _ -> False+ formOf (PrivKeyMLDSA44 k) = Just (privkeyMLDSA_form k)+ formOf (PrivKeyMLDSA65 k) = Just (privkeyMLDSA_form k)+ formOf (PrivKeyMLDSA87 k) = Just (privkeyMLDSA_form k)+ formOf _ = Nothing++-- | 'show' of an ML-DSA private key holds neither the seed nor the key,+-- and 'debugShow' holds both.+property_mldsa_show_redacts :: MLDSASeed -> Bool+property_mldsa_show_redacts (MLDSASeed seed) = all ok (map fst (mldsaForms seed))+ where+ hex = concatMap byte . B.unpack+ byte w = [digit (w `div` 16), digit (w `mod` 16)]+ digit n = "0123456789abcdef" !! fromIntegral n+ ok form =+ let k =+ throwCryptoError $+ privkeyMLDSAFromSeed (Proxy :: Proxy MLDSA.MLDSA44) form seed+ wrapped = PrivKeyMLDSA44 k+ shown = show k ++ show wrapped+ debugged = debugShow k ++ debugShow wrapped+ expanded = hex (mldsaExpanded seed)+ in not (hex seed `isInfixOf` shown)+ && not (expanded `isInfixOf` shown)+ && expanded `isInfixOf` debugged+ && (form == MLKeyExpanded || hex seed `isInfixOf` debugged)++property_mldsa_mismatch :: MLDSASeed -> MLDSASeed -> Property+property_mldsa_mismatch (MLDSASeed seed1) (MLDSASeed seed2) =+ seed1 /= seed2 ==>+ either (const True) (const False) $+ mldsaPKCS8+ [ Start Sequence+ , OctetString seed1+ , OctetString (mldsaExpanded seed2)+ , End Sequence+ ]++instance Arbitrary AltName where+ arbitrary =+ oneof+ [ AltNameDNS <$> arbitraryHost+ , AltNameRFC822 . ("user@" ++) <$> arbitraryHost+ , 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 =+ GeneralSubtree+ <$> (arbitrary >>= base)+ <*> pure 0+ <*> oneof [pure Nothing, Just <$> choose (0, 300)]+ where+ -- an address with a mask+ base (AltNameIP _) = AltNameIP . B.pack <$> (elements [8, 32] >>= vector)+ base a = return a++instance Arbitrary ExtNameConstraints where+ arbitrary = ExtNameConstraints <$> arbitrary <*> arbitrary++instance Arbitrary ExtSubjectAltName where+ arbitrary = ExtSubjectAltName <$> arbitrary++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+ , 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++-- NameConstraints with permitted dNSName "example.com" and+-- excluded iPAddress 10.0.0.0/8, as encoded by OpenSSL.+property_name_constraints_der :: Bool+property_name_constraints_der =+ extensionDecode raw+ == Just+ ( Right $+ ExtNameConstraints+ [GeneralSubtree (AltNameDNS "example.com") 0 Nothing]+ [GeneralSubtree (AltNameIP (B.pack [10, 0, 0, 0, 255, 0, 0, 0])) 0 Nothing]+ )+ && extensionEncode+ True+ (either error id (fromJust (extensionDecode raw)) :: ExtNameConstraints)+ == raw+ where+ raw = ExtensionRaw [2, 5, 29, 30] True der+ der =+ B.pack $+ [0x30, 0x1f, 0xa0, 0x0f, 0x30, 0x0d, 0x82, 0x0b]+ ++ map (fromIntegral . fromEnum) "example.com"+ ++ [0xa1, 0x0c, 0x30, 0x0a, 0x87, 0x08, 10, 0, 0, 0, 255, 0, 0, 0]++-- Unknown key usage bits and a bogus bit string length are ignored.+property_key_usage_unknown_bits :: Bool+property_key_usage_unknown_bits =+ extDecode [BitString (toBitArray (B.pack [0x80, 0x40]) 6)]+ == Right (ExtKeyUsage [KeyUsage_digitalSignature])+ && extDecode [BitString (toBitArray B.empty 7)] == Right (ExtKeyUsage [])++property_malformed_extensions :: Bool+property_malformed_extensions =+ isLeft+ ( extDecode [Start Sequence, IntVal 1, End Sequence]+ :: Either String ExtExtendedKeyUsage+ )+ && isLeft+ ( extDecode [Start Sequence, End Sequence]+ :: Either String ExtCrlDistributionPoints+ )+ where+ isLeft = either (const True) (const False)++-- Unsupported GeneralName types in a SAN are skipped, but not in constraints.+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]+ 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 =+ [ Start (Container Context 0)+ , OID [1, 2, 3]+ , Start (Container Context 0)+ , IntVal 1+ , End (Container Context 0)+ , End (Container Context 0)+ ]++-- A certificate whose validity cannot be decoded is rejected with 'Left'+-- rather than an exception thrown lazily from the decoder.+property_lazy_decode_error :: Bool+property_lazy_decode_error =+ case decodeSignedCertificate corrupted of+ Left e -> length e > 0+ Right _ -> False+ where+ t = timeConvert (Date 2020 January 1) :: DateTime+ dn = DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")]+ cert =+ Certificate+ 2+ 1+ (SignatureALG HashSHA256 PubKeyALG_RSA)+ dn+ (t, t)+ dn+ (PubKeyRSA (RSA.PublicKey 1 0x7f 3))+ (Extensions Nothing)+ encoded =+ encodeSignedObject $+ fst $+ objectToSignedExact+ (\_ -> (B.pack [1], SignatureALG HashSHA256 PubKeyALG_RSA, ()))+ cert+ -- replace the first character of the first UTCTime with a non-ASCII byte+ (before, rest) = B.breakSubstring (B.pack [0x17, 0x0d]) encoded+ corrupted = before <> B.pack [0x17, 0x0d, 0xff] <> B.drop 3 rest++-- | A certificate re-encoded after modifying its ASN.1 stream.+modifiedCertificate :: ([ASN1] -> [ASN1]) -> Either String SignedCertificate+modifiedCertificate f = decodeSignedCertificate $ encodeASN1' DER $ f asn1+ where+ t = timeConvert (Date 2020 January 1) :: DateTime+ dn = DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")]+ cert =+ Certificate+ 2+ 1+ (SignatureALG HashSHA256 PubKeyALG_RSA)+ dn+ (t, t)+ dn+ (PubKeyRSA (RSA.PublicKey 1 0x7f 3))+ (Extensions Nothing)+ encoded =+ encodeSignedObject $+ fst $+ objectToSignedExact+ (\_ -> (B.pack [1], SignatureALG HashSHA256 PubKeyALG_RSA, ()))+ cert+ asn1 = either (error . show) id $ decodeASN1' DER encoded++isLeft' :: Either a b -> Bool+isLeft' = either (const True) (const False)++property_signed_strict :: Bool+property_signed_strict =+ not (isLeft' (modifiedCertificate id))+ && isLeft' (modifiedCertificate (++ [IntVal 1]))+ && isLeft' (modifiedCertificate (\l -> init l ++ [IntVal 1, End Sequence]))+ && isLeft' (modifiedCertificate (\l -> Start Set : init (drop 1 l) ++ [End Set]))++property_duplicate_extensions :: Bool+property_duplicate_extensions =+ isLeft'+ ( fromASN1 (toASN1 (Extensions (Just [e, e])) [])+ :: Either String (Extensions, [ASN1])+ )+ where+ e = extensionEncode False (ExtKeyUsage [KeyUsage_digitalSignature])++-- Data after the RSA key in the BIT STRING must not be parsed as+-- following fields.+property_rsa_pubkey_trailing :: Bool+property_rsa_pubkey_trailing =+ not (isLeft' (decode key)) && isLeft' (decode (key ++ [IntVal 1]))+ where+ key = [Start Sequence, IntVal 0xc5, IntVal 3, End Sequence]+ decode k =+ fromASN1+ [ Start Sequence+ , Start Sequence+ , OID [1, 2, 840, 113549, 1, 1, 1]+ , Null+ , End Sequence+ , BitString (toBitArray (encodeASN1' DER k) 0)+ , End Sequence+ ]+ :: Either String (PubKey, [ASN1])++property_pss_hash :: Bool+property_pss_hash =+ decode (pss [2, 16, 840, 1, 101, 3, 4, 2, 1])+ == Right (SignatureALG HashSHA256 PubKeyALG_RSAPSS, [])+ -- sha256WithRSAEncryption is not a hash algorithm+ && isLeft' (decode (pss [1, 2, 840, 113549, 1, 1, 11]))+ -- a bare hash algorithm is not a signature algorithm+ && decode [Start Sequence, OID sha256, End Sequence]+ == Right (SignatureALG_Unknown sha256, [])+ && decode (toASN1 (SignatureALG HashSHA384 PubKeyALG_RSAPSS) [])+ == Right (SignatureALG HashSHA384 PubKeyALG_RSAPSS, [])+ where+ sha256 = [2, 16, 840, 1, 101, 3, 4, 2, 1]+ decode l = fromASN1 l :: Either String (SignatureALG, [ASN1])+ pss h =+ [ Start Sequence+ , OID [1, 2, 840, 113549, 1, 1, 10]+ , Start Sequence+ , Start (Container Context 0)+ , Start Sequence+ , OID h+ , End Sequence+ , End (Container Context 0)+ , Start (Container Context 1)+ , Start Sequence+ , OID [1, 2, 840, 113549, 1, 1, 8]+ , Start Sequence+ , OID h+ , End Sequence+ , End Sequence+ , End (Container Context 1)+ , Start (Container Context 2)+ , IntVal 32+ , End (Container Context 2)+ , End Sequence+ , End Sequence+ ]++-- Malformed inner encodings of PKCS#8 keys return Left, not an exception.+property_privkey_malformed :: Bool+property_privkey_malformed =+ all+ isLeft'+ [ decode [1, 2, 840, 113549, 1, 1, 1] Null rsaInner+ , decode [1, 3, 101, 112] none edInner+ ]+ where+ rsaInner = B.pack [0x30, 0x05, 0x02, 0x00, 0x02, 0x01, 0x00]+ edInner = B.pack [0x17, 0x01, 0xff]+ none = End Sequence+ decode oid param inner =+ fromASN1+ ( [Start Sequence, IntVal 0, Start Sequence, OID oid]+ ++ (if param == none then [] else [param])+ ++ [End Sequence, OctetString inner, End Sequence]+ )+ :: Either String (PrivKey, [ASN1])++sampleCert :: Certificate+sampleCert =+ Certificate+ 2+ 1+ (SignatureALG HashSHA256 PubKeyALG_RSA)+ dn+ (t, t)+ dn+ (PubKeyRSA (RSA.PublicKey 1 0x7f 3))+ (Extensions Nothing)+ where+ t = timeConvert (Date 2020 January 1) :: DateTime+ dn = DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")]++decodeCert :: [ASN1] -> Either String (Certificate, [ASN1])+decodeCert = fromASN1++property_key_usage_der :: Bool+property_key_usage_der =+ extEncodeBs (ExtKeyUsage [KeyUsage_digitalSignature]) == B.pack [3, 2, 7, 0x80]+ && extEncodeBs (ExtKeyUsage [KeyUsage_keyCertSign, KeyUsage_cRLSign])+ == B.pack [3, 2, 1, 0x06]+ && extEncodeBs (ExtKeyUsage [KeyUsage_digitalSignature, KeyUsage_decipherOnly])+ == B.pack [3, 3, 7, 0x80, 0x80]+ && extEncodeBs (ExtKeyUsage []) == B.pack [3, 1, 0]++property_basic_constraints_no_ca :: Bool+property_basic_constraints_no_ca =+ extDecode [Start Sequence, IntVal 0, End Sequence]+ == Right (ExtBasicConstraints False (Just 0))++property_aki_issuer_serial :: Bool+property_aki_issuer_serial =+ 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)+ }++-- Unknown keys are kept as PubKeyUnknown, with or without parameters.+property_unknown_pubkey :: Bool+property_unknown_pubkey =+ decode [] == Right (PubKeyUnknown oid key, [])+ && decode [Start Sequence, End Sequence] == Right (PubKeyUnknown oid key, [])+ where+ oid = [1, 2, 3, 4]+ key = B.pack [1, 2, 3]+ decode params =+ fromASN1+ ( [Start Sequence, Start Sequence, OID oid]+ ++ params+ ++ [End Sequence, BitString (toBitArray key 0), End Sequence]+ )+ :: Either String (PubKey, [ASN1])++property_ec_prime_roundtrip :: Bool+property_ec_prime_roundtrip = fromASN1 (toASN1 key []) == Right (key, [])+ where+ key =+ PubKeyEC+ PubKeyEC_Prime+ { pubkeyEC_pub = SerializedPoint (B.pack [4, 1, 2])+ , pubkeyEC_a = 3+ , pubkeyEC_b = 0x1234+ , pubkeyEC_prime = 0xfffffffffffffffffffffffffffffffeffffffffffffffff+ , pubkeyEC_generator = SerializedPoint (B.pack [4, 5, 6])+ , pubkeyEC_order = 0xffffffffffffffffffffffff99def836146bc9b1b4d22831+ , pubkeyEC_cofactor = 1+ , pubkeyEC_seed = 0x3045ae6fc8422f64ed579528d38120eae12196d5+ }++property_unique_ids :: Bool+property_unique_ids =+ decodeCert (toASN1 sampleCert [] ++ [Other Context 1 b, Other Context 2 b])+ == Right (sampleCert, [])+ && isLeft' (decodeCert (toASN1 sampleCert{certVersion = 3} []))+ where+ b = B.pack [0, 1]++-- Times with a zone offset are converted to UTC, and UTCTime is used+-- from 1950 through 2049.+property_validity_time :: Bool+property_validity_time =+ fmap (certValidity . fst) (decodeCert (map withOffset (toASN1 sampleCert [])))+ == Right (t', t')+ && map timeType (validity 1949) == [TimeGeneralized]+ && map timeType (validity 1950) == [TimeUTC]+ && map timeType (validity 2049) == [TimeUTC]+ && map timeType (validity 2050) == [TimeGeneralized]+ where+ (t, _) = certValidity sampleCert+ t' = timeAdd t (Hours (-9))+ withOffset (ASN1Time ty d _) = ASN1Time ty d (Just (TimezoneOffset 540))+ withOffset a = a+ validity y =+ take+ 1+ [ a+ | a@ASN1Time{} <-+ toASN1 sampleCert{certValidity = (year y, year y)} []+ ]+ year y = timeConvert (Date y January 1) :: DateTime+ timeType (ASN1Time ty _ _) = ty+ timeType _ = TimeUTC++property_crl_v1 :: Bool+property_crl_v1 =+ take 1 encoded /= [IntVal 0]+ && fromASN1 encoded == Right (crl, [])+ where+ t = timeConvert (Date 2020 January 1) :: DateTime+ crl =+ CRL+ 0+ (SignatureALG HashSHA256 PubKeyALG_RSA)+ (DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")])+ t+ Nothing+ []+ (Extensions Nothing)+ encoded = toASN1 crl []++-- RFC 5915: the private key octet string is as long as the order.+property_ec_privkey_length :: Bool+property_ec_privkey_length =+ [B.length o | OctetString o <- asn1] == [32]+ && fromASN1 asn1 == Right (key, [])+ where+ key = PrivKeyEC (PrivKeyEC_Named ECC.SEC_p256r1 1)+ asn1 = toASN1 key []++-- Explicit parameters name a curve only if the generator and the+-- cofactor match too.+property_ec_curve_name :: Bool+property_ec_curve_name =+ ecPubKeyCurveName (explicit g 1) == Just ECC.SEC_p256r1+ && ecPubKeyCurveName (explicit (ECC.pointMul curve 2 g) 1) == Nothing+ && ecPubKeyCurveName (explicit g 2) == Nothing+ where+ curve = ECC.getCurveByName ECC.SEC_p256r1+ cc = ECC.common_curve curve+ p = case curve of+ ECC.CurveFP (ECC.CurvePrime q _) -> q+ _ -> 0+ g = ECC.ecc_g cc+ point (ECC.Point x y) = SerializedPoint (B.cons 4 (i2ospOf_ 32 x <> i2ospOf_ 32 y))+ point ECC.PointO = SerializedPoint (B.singleton 0)+ explicit gen h =+ PubKeyEC_Prime+ { pubkeyEC_pub = point g+ , pubkeyEC_a = ECC.ecc_a cc+ , pubkeyEC_b = ECC.ecc_b cc+ , pubkeyEC_prime = p+ , pubkeyEC_generator = point gen+ , pubkeyEC_order = ECC.ecc_n cc+ , pubkeyEC_cofactor = h+ , pubkeyEC_seed = 0+ }++property_pss_default :: Bool+property_pss_default =+ fromASN1 asn1 == Right (SignatureALG HashSHA1 PubKeyALG_RSAPSS, [])+ && toASN1 (SignatureALG HashSHA1 PubKeyALG_RSAPSS) [] == asn1+ where+ asn1 =+ [ Start Sequence+ , OID [1, 2, 840, 113549, 1, 1, 10]+ , Start Sequence+ , End Sequence+ , 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, 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 simple)+ && extEncodeBs simple == der+ && extDecode+ ( [Start Sequence]+ ++ dp (uriName ++ [Other Context 1 (B.pack [6, 0x40])] ++ issuer)+ ++ dp issuer+ ++ [End Sequence]+ )+ == 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]+ ++ map (fromIntegral . fromEnum) url+ )+ uriName =+ [ Start (Container Context 0)+ , Start (Container Context 0)+ , Other Context 6 (B.pack (map (fromIntegral . fromEnum) url))+ , End (Container Context 0)+ , End (Container Context 0)+ ]+ issuer =+ [ Start (Container Context 2)+ , Other Context 2 (B.pack [0x61])+ , End (Container Context 2)+ ]+ dp xs = [Start Sequence] ++ xs ++ [End Sequence]++property_extension_id :: (Show e, Eq e, Extension e) => e -> Bool+property_extension_id e = case extDecode (extEncode e) of+ Left err -> error err+ Right v+ | v == e -> True+ | otherwise -> error ("expected " ++ show e ++ " got: " ++ show v)++-- 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, 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 []+ | pub == PubKeyALG_RSA = Null `elem` toASN1 alg []+property_sig_alg_parameters alg@(SignatureALG_IntrinsicHash _) =+ Null `notElem` toASN1 alg []+property_sig_alg_parameters _ = True++main =+ defaultMain $+ testGroup+ "X509"+ [ testGroup+ "marshall"+ [ testProperty "pubkey" (property_unmarshall_marshall_id :: PubKey -> Bool)+ , testProperty "privkey" (property_unmarshall_marshall_id :: PrivKey -> Bool)+ , testProperty+ "signature alg"+ (property_unmarshall_marshall_id :: SignatureALG -> Bool)+ , testGroup+ "extension"+ [ testProperty "key-usage" (property_extension_id :: ExtKeyUsage -> Bool)+ , testProperty+ "extended-key-usage"+ (property_extension_id :: ExtExtendedKeyUsage -> Bool)+ , testProperty+ "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+ , testProperty+ "name-constraints"+ (property_extension_id :: ExtNameConstraints -> Bool)+ , testProperty "name-constraints DER" property_name_constraints_der+ ]+ , testGroup+ "malformed"+ [ testProperty "key-usage unknown bits" property_key_usage_unknown_bits+ , testProperty "extensions" property_malformed_extensions+ , 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+ , testProperty "RSA key trailing data" property_rsa_pubkey_trailing+ , testProperty "PSS hash" property_pss_hash+ , testProperty "private key" property_privkey_malformed+ ]+ , testGroup+ "interoperability"+ [ testProperty "KeyUsage DER" property_key_usage_der+ , testProperty "BasicConstraints without cA" property_basic_constraints_no_ca+ , testProperty "AKI with issuer and serial" property_aki_issuer_serial+ , testProperty "unknown public key" property_unknown_pubkey+ , testProperty "EC explicit parameters" property_ec_prime_roundtrip+ , testProperty "unique IDs" property_unique_ids+ , 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+ ]+ , testGroup+ "signature-alg-parameters"+ [ testProperty+ "per-family"+ property_sig_alg_parameters+ ]+ , testProperty+ "extensions"+ (property_unmarshall_marshall_id :: Extensions -> Bool)+ , testProperty+ "certificate"+ (property_unmarshall_marshall_id :: Certificate -> Bool)+ , testProperty "crl" (property_unmarshall_marshall_id :: CRL -> Bool)+ ]+ , testGroup+ "show"+ [testProperty "ec privkey is redacted" property_ec_show_redacts]+ , testGroup+ "ML-DSA private key"+ [ testProperty "seed, expandedKey and both" property_mldsa_forms+ , testProperty+ "each form is written back as itself"+ property_mldsa_form_round_trip+ , testProperty+ "a generated seed survives the round trip"+ property_mldsa_generated_seed+ , testProperty+ "a key OpenSSL wrote reads and writes back unchanged"+ (property_mldsa_openssl)+ , testProperty "both refused if they disagree" property_mldsa_mismatch+ , testProperty "is redacted" property_mldsa_show_redacts+ ]+ ]
crypton-x509.cabal view
@@ -1,64 +1,76 @@-Name: crypton-x509-version: 1.7.7-Description: X509 reader and writer. please see README-License: BSD3-License-file: LICENSE-Copyright: Vincent Hanquez <vincent@snarc.org>-Author: Vincent Hanquez <vincent@snarc.org>-Maintainer: Kazu Yamamoto <kazu@iij.ad.jp>-Synopsis: X509 reader and writer-Build-Type: Simple-Category: Data-stability: experimental-Homepage: https://github.com/kazu-yamamoto/crypton-certificate-Cabal-Version: >= 1.10+cabal-version: >=1.10+name: crypton-x509+version: 1.11.0+license: BSD3+license-file: LICENSE+copyright: Vincent Hanquez <vincent@snarc.org>+maintainer: Kazu Yamamoto <kazu@iij.ad.jp>+author: Vincent Hanquez <vincent@snarc.org>+stability: experimental+homepage: https://github.com/kazu-yamamoto/crypton-certificate+synopsis: X509 reader and writer+description: X509 reader and writer. please see README+category: Data+build-type: Simple+extra-source-files: ChangeLog.md -Library- Default-Language: Haskell2010- Build-Depends: base >= 4.7 && < 5- , bytestring- , memory- , transformers >= 0.4- , containers- , hourglass- , pem >= 0.1- , asn1-types >= 0.3.1 && < 0.4- , asn1-encoding >= 0.9 && < 0.10- , asn1-parse >= 0.9.3 && < 0.10- , crypton >= 0.24- Exposed-modules: Data.X509- Data.X509.EC- Other-modules: Data.X509.Internal- Data.X509.CertificateChain- Data.X509.AlgorithmIdentifier- Data.X509.DistinguishedName- Data.X509.Cert- Data.X509.PublicKey- Data.X509.PrivateKey- Data.X509.Ext- Data.X509.ExtensionRaw- Data.X509.CRL- Data.X509.OID- Data.X509.Signed- ghc-options: -Wall+source-repository head+ type: git+ location: https://github.com/kazu-yamamoto/crypton-certificate+ subdir: crypton-x509 -Test-Suite test-x509- Default-Language: Haskell2010- type: exitcode-stdio-1.0- hs-source-dirs: Tests- Main-is: Tests.hs- Build-Depends: base >= 3 && < 5- , bytestring- , mtl- , tasty- , tasty-quickcheck- , hourglass- , asn1-types- , crypton-x509- , crypton- ghc-options: -Wall -fno-warn-orphans -fno-warn-missing-signatures+library+ exposed-modules:+ Data.X509+ Data.X509.EC -source-repository head- type: git- location: https://github.com/kazu-yamamoto/crypton-certificate- subdir: x509+ other-modules:+ Data.X509.Internal+ Data.X509.CertificateChain+ Data.X509.AlgorithmIdentifier+ Data.X509.DistinguishedName+ Data.X509.Cert+ Data.X509.PublicKey+ Data.X509.PrivateKey+ Data.X509.Ext+ Data.X509.ExtensionRaw+ Data.X509.CRL+ Data.X509.OID+ Data.X509.Signed++ default-language: Haskell2010+ ghc-options: -Wall+ build-depends:+ base >=4.7 && <5,+ bytestring,+ containers,+ 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,+ crypton-pem >=0.2.4 && <0.4,+ ram,+ time-hourglass,+ transformers >=0.4++test-suite test-x509+ type: exitcode-stdio-1.0+ main-is: Tests.hs+ other-modules:+ MLDSAKeys+ MLKEMKeys+ hs-source-dirs: Tests+ default-language: Haskell2010+ ghc-options: -Wall -fno-warn-orphans -fno-warn-missing-signatures+ build-depends:+ base >=3 && <5,+ bytestring,+ crypton,+ crypton-x509,+ crypton-asn1-encoding,+ crypton-asn1-types,+ mtl,+ ram,+ tasty,+ tasty-quickcheck,+ time-hourglass