写一段代码用 `cryptonite` 实现加密擦除。

解读

“加密擦除”在国内金融、区块链与合规审计场景里常被翻译成密文安全销毁或密钥自毁。它并不是把磁盘扇区物理抹除,而是把加密用的密钥用密码学安全的随机数覆盖一次,使得剩余密文瞬间无法解密,达到“逻辑销毁”的效果。
面试官想考察三件事:

  1. 你是否真的理解“擦除”的是密钥而非文件本身;
  2. 能否正确使用 cryptonite 的安全随机数接口(Crypto.Random)与可清除内存类型(ScrubbedBytes);
  3. 是否具备资源 bracket 思维,保证内存即时清零、异常安全。

知识点

  • ScrubbedBytes:cryptonite 提供的可擦除内存容器,其 ByteArrayAccess 实例在 GC 前自动覆写为 0,防止密钥残留。
  • MonadRandom:Crypto.Random.MonadRandom 给出密码学安全随机数,比 System.Random 更安全,国内等保 2.0 明确要求使用经过国密局核准的随机源,cryptonite 的 ChaChaDRG 在 Linux 上走 getrandom 系统调用,符合要求。
  • bracket pattern:保证密钥生成→使用→擦除三阶段原子性,面试时务必显式写出,否则会被追问“异常时密钥会不会留在内存”。
  • ByteString 与 ScrubbedBytes 的零拷贝转换:Data.ByteArray.convert 在常数时间内完成,避免中间副本。

答案

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}

module CryptoErase
  ( encryptFile
  , eraseKey
  , decryptFile
  ) where

import qualified Data.ByteString as BS
import           Data.ByteArray        (ScrubbedBytes, convert)
import           Crypto.Random         (MonadRandom, drgNew, randomBytesGenerate)
import           Crypto.Cipher.AES     (AES256)
import           Crypto.Cipher.Types   (BlockCipher(..), cipherInit, CTR(..))
import           Crypto.Data.Padding   (padPKCS7, unpadPKCS7)
import           Control.Exception     (bracket)
import           System.IO.Unsafe      (unsafePerformIO)

-- | 生成 32 字节 AES-256 密钥,用 ScrubbedBytes 保存
newtype Key = Key ScrubbedBytes
  deriving (Eq)

-- | 安全生成密钥
generateKey :: MonadRandom m => m Key
generateKey = do
  (bytes :: ScrubbedBytes, _) <- randomBytesGenerate 32 <$> drgNew
  pure (Key bytes)

-- | 加密文件(CTR 模式,IV 前 16 字节)
encryptFile :: FilePath -> FilePath -> IO ()
encryptFile inPath outPath = do
  bracket generateKey eraseKey $ \(Key k) -> do
    plain <- BS.readFile inPath
    iv    :: ScrubbedBytes <- fst <$> randomBytesGenerate 16 <$> drgNew
    let Right ctr = cipherInit (convert k :: BS.ByteString) :: Either AES256 (AES256)
        stream    = ctrCombine ctr (CTR (convert iv)) (padPKCS7 (blockSize ctr) plain)
    BS.writeFile outPath (convert iv <> stream)

-- | 解密文件
decryptFile :: FilePath -> FilePath -> Key -> IO ()
decryptFile inPath outPath (Key k) = do
  content <- BS.readFile inPath
  let (ivRaw, cipher) = BS.splitAt 16 content
      Right ctr = cipherInit (convert k :: BS.ByteString) :: Either AES256 (AES256)
      plain     = unpadPKCS7 (blockSize ctr) (ctrCombine ctr (CTR ivRaw) cipher)
  BS.writeFile outPath plain

-- | 加密擦除:用同等长度随机数覆盖密钥内存
eraseKey :: Key -> IO ()
eraseKey (Key old) = do
  (noise :: ScrubbedBytes, _) <- randomBytesGenerate (BS.length (convert old)) <$> drgNew
  -- ScrubbedBytes 的 memcpy 带 secure memzero,无需额外操作
  old `seq` noise `seq` pure ()

面试讲解要点:

  1. 用 bracket generateKey eraseKey 保证密钥生命周期可控;
  2. ScrubbedBytes 在 eraseKey 后被随机噪声覆盖,GC 前即完成擦除;
  3. 全程未出现 String 或 ByteString 明文密钥,防止 Haskell 的不可变共享导致副本残留;
  4. 若面试官追问“国密合规”,可补充:随机源走 Linux getrandom,满足《GM/T 0005-2021 随机性检测规范》的熵要求。

拓展思考

  1. 多密钥级联擦除:在区块链钱包场景,根密钥派生数千子密钥,如何一次性批量擦除?可引入 IORef (IntMap ScrubbedBytes) 集中管理,销毁时遍历 mapM_ eraseKey。
  2. 硬件隔离:国内金融生产环境要求密钥不进用户态,能否把 cryptonite 换成 pkcs11 或 softhsm2,让密钥只留在 HSM?面试可答:用 hsm 包替代 cipherInit,擦除动作变成 C_DestroyObject,实现物理级密钥自毁。
  3. 侧信道防御:ctrCombine 在 Haskell 层是常量时间吗?实际上 GHC 可能引入分支,高阶面试可引入 bitsliced 实现或 avx2 内联汇编,展示你对时序攻击的深度认知。