写一段代码用 `cryptonite` 实现加密擦除。
解读
“加密擦除”在国内金融、区块链与合规审计场景里常被翻译成密文安全销毁或密钥自毁。它并不是把磁盘扇区物理抹除,而是把加密用的密钥用密码学安全的随机数覆盖一次,使得剩余密文瞬间无法解密,达到“逻辑销毁”的效果。
面试官想考察三件事:
- 你是否真的理解“擦除”的是密钥而非文件本身;
- 能否正确使用
cryptonite的安全随机数接口(Crypto.Random)与可清除内存类型(ScrubbedBytes); - 是否具备资源 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 ()
面试讲解要点:
- 用
bracket generateKey eraseKey保证密钥生命周期可控; ScrubbedBytes在eraseKey后被随机噪声覆盖,GC 前即完成擦除;- 全程未出现
String或ByteString明文密钥,防止 Haskell 的不可变共享导致副本残留; - 若面试官追问“国密合规”,可补充:随机源走 Linux
getrandom,满足《GM/T 0005-2021 随机性检测规范》的熵要求。
拓展思考
- 多密钥级联擦除:在区块链钱包场景,根密钥派生数千子密钥,如何一次性批量擦除?可引入
IORef (IntMap ScrubbedBytes)集中管理,销毁时遍历mapM_ eraseKey。 - 硬件隔离:国内金融生产环境要求密钥不进用户态,能否把
cryptonite换成pkcs11或softhsm2,让密钥只留在 HSM?面试可答:用hsm包替代cipherInit,擦除动作变成C_DestroyObject,实现物理级密钥自毁。 - 侧信道防御:
ctrCombine在 Haskell 层是常量时间吗?实际上 GHC 可能引入分支,高阶面试可引入bitsliced实现或avx2内联汇编,展示你对时序攻击的深度认知。