-- KeyInfo.hs: OpenPGP (RFC4880) fingerprinting methods
-- Copyright © 2012-2016  Clint Adams
-- This software is released under the terms of the Expat license.
-- (See the LICENSE file).

module Codec.Encryption.OpenPGP.KeyInfo (
   pubkeySize
 , pkalgoAbbrev
) where

import qualified Crypto.PubKey.RSA as RSA
import qualified Crypto.PubKey.DSA as DSA
import Data.Bits (shiftR)
import Data.List (unfoldr)

import Codec.Encryption.OpenPGP.Types

pubkeySize :: PKey -> Either String Int
pubkeySize (RSAPubKey (RSA_PublicKey x)) = Right (RSA.public_size x * 8)
pubkeySize (DSAPubKey (DSA_PublicKey x)) = Right (bitcount . DSA.params_p . DSA.public_params $ x)
pubkeySize (ElGamalPubKey p _ _) = Right (bitcount p)
pubkeySize x = Left $ "Unable to calculate size of " ++ show x

bitcount :: Integer -> Int
bitcount = (*8) . length . unfoldr (\x -> if x == 0 then Nothing else Just (True, x `shiftR` 8))

-- FIXME: redo these for hOpenPGP 3
pkalgoAbbrev :: PubKeyAlgorithm -> String
pkalgoAbbrev RSA = "R"
pkalgoAbbrev DSA = "D"
pkalgoAbbrev ElgamalEncryptOnly = "g"
pkalgoAbbrev DeprecatedRSAEncryptOnly = "-"
pkalgoAbbrev DeprecatedRSASignOnly = "_"
pkalgoAbbrev ECDH = "e"
pkalgoAbbrev ECDSA = "E"
pkalgoAbbrev ForbiddenElgamal = "f"
pkalgoAbbrev DH = "d"
pkalgoAbbrev (OtherPKA _) = "."