3

我有一个函数可以读取带有 HsOpenSslreadPrivateKey函数的 Rsa 密钥,不幸的是我的函数的签名是 this String -> IO (Maybe (IO Maybe RsaKey))。我需要 PEM 格式和 Cryptonite.RSA 密钥,我编写了函数mkRsaKey来从 PEM 格式的字符串中生成它。

继承人的代码:

import qualified Crypto.PubKey.RSA as Rsa --from cryptonite
import OpenSSL.EVP.PKey -- from HsOpenSSL
import OpenSSL.PEM -- from HsOpenSSL
import OpenSSL.RSA -- from HsOpenSSL
import Prelude

data RsaKey = RsaKey
  { rsaKeyCryptoniteKey :: Rsa.PrivateKey,
    rsaKeyStringRepr :: String
  }
  deriving (Show)

openSslKeyToCryptoniteKey :: RSAKeyPair -> Maybe Rsa.PrivateKey
openSslKeyToCryptoniteKey key = do
  let d = rsaD key
  let p = rsaP key
  let q = rsaQ key
  let mdP = rsaDMP1 key
  let mdQ = rsaDMQ1 key
  let mqinv = rsaIQMP key
  let size = rsaSize key
  let n = rsaN key
  let e = rsaE key
  dP <- mdP
  dQ <- mdQ
  qinv <- mqinv

  let pub = Rsa.PublicKey size n e
  return $ Rsa.PrivateKey pub d p q dP dQ qinv

openSslKeyToRsaKey :: RSAKeyPair -> IO (Maybe RsaKey)
openSslKeyToRsaKey key = do
  stringRepr <- writePublicKey key
  let maybeCryptoKey = openSslKeyToCryptoniteKey key
  return $ do
    cryptoKey <- maybeCryptoKey
    return $ RsaKey cryptoKey stringRepr

mkRsaKey :: String -> IO (Maybe (IO (Maybe RsaKey)))
mkRsaKey privateKey = do
  someOpenSslKey <- readPrivateKey privateKey PwNone
  let openSslKey = toKeyPair someOpenSslKey
  return $ openSslKeyToRsaKey <$> openSslKey

现在你可以看到类型签名在我的意义上不是我想要的最佳选择IO (Maybe RsaKey)。我怎样才能做到这一点?

编辑:

我实际上设法做到了,但我正在使用unsafePerformIO

mkRsaKey :: String -> IO (Maybe RsaKey)
mkRsaKey privateKey = do
  someOpenSslKey <- readPrivateKey privateKey PwNone
  return $ do
    openSslKey <- toKeyPair someOpenSslKey
    unsafePerformIO (openSslKeyToRsaKey $ openSslKey)

据我所知,你永远不应该使用unsafePerformIO没有它有什么方法可以做到这一点吗?

4

2 回答 2

5

很好的发现case。这绝对不是你应该使用的地方unsafePerformIO。这是一个更紧凑的方式,为了好玩。

flattenMaybe :: (Monad m) => m (Maybe (m (Maybe a))) -> m (Maybe a)
flattenMaybe m = m >>= fromMaybe (return Nothing)

为了更有趣,像这样扁平化层的能力是单子的特征能力;我们只是在 上使用该能力m (Maybe ...),也称为MaybeT。所以我们也可以这样写:

flattenMaybe = runMaybeT . join . fmap MaybeT . MaybeT

进行必要的包装/展开以使用joinat MaybeT m (MaybeT m a) -> MaybeT m a

于 2021-12-22T09:12:01.713 回答
4

找到一种没有unsafePerformIO技巧的方法是使用 case 语句,该语句仅在Nothingcase 中使用 return 函数。这是实现:

mkRsaKey :: String -> IO (Maybe RsaKey)
mkRsaKey privateKey = do
  someOpenSslKey <- readPrivateKey privateKey PwNone
  let maybeOpenSslKey = toKeyPair someOpenSslKey
  case maybeOpenSslKey of
    Just key -> openSslKeyToRsaKey key
    Nothing -> return Nothing
于 2021-12-22T08:21:37.490 回答