1 -- This file is part of htalkat
2 -- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
4 -- This program is free software: you can redistribute it and/or modify
5 -- it under the terms of version 3 of the GNU General Public License as
6 -- published by the Free Software Foundation, or any later version.
8 -- You should have received a copy of the GNU General Public License
9 -- along with this program. If not, see http://www.gnu.org/licenses/.
11 module Certificate
where
14 import Data
.ASN1
.BinaryEncoding
(DER
(..))
15 import Data
.ASN1
.Encoding
(encodeASN1
')
16 import Data
.ASN1
.Types
(ASN1Object
(..))
17 import Data
.ByteArray
(convert
)
19 import qualified Data
.ByteString
as BS
20 import qualified Data
.Text
as TS
21 import qualified Data
.Text
.Encoding
as TS
22 import qualified Data
.X509
as X
26 newtype Certificate
= Certificate X
.SignedCertificate
29 takeTailCert
:: X
.CertificateChain
-> Maybe Certificate
30 takeTailCert
(X
.CertificateChain
(c
:_
)) = Just
$ Certificate c
31 takeTailCert _
= Nothing
33 -- |First 16 bytes of sha256 hash of DER encoding of SPKI field
34 -- (as suggested by RFC7469).
35 spkiFingerprint
:: Certificate
-> Fingerprint
36 spkiFingerprint
(Certificate signed
) = truncateFP
16 . Fingerprint
. convert
. hashWith SHA256
.
37 encodeDER
. X
.certPubKey
. X
.signedObject
$ X
.getSigned signed
39 truncateFP
:: Int -> Fingerprint
-> Fingerprint
40 truncateFP n
(Fingerprint fp
) = Fingerprint
$ BS
.take n fp
41 encodeDER
:: ASN1Object o
=> o
-> BS
.ByteString
42 encodeDER
= encodeASN1
' DER
. (`toASN1`
[])
44 certCN
:: Certificate
-> String
45 certCN
(Certificate signed
) = maybe "" (TS
.unpack
. TS
.decodeUtf8
. X
.getCharacterStringRawData
)
46 . X
.getDnElement X
.DnCommonName
. X
.certIssuerDN
$ X
.getCertificate signed