Haskell AES加密
1.
-- | Key to encrypt data newtype AesKey = AesKey { fromAESKey :: ByteString } deriving (Show, Eq, Generic, Hashable) deriveAesKey :: Text -> AesKey deriveAesKey = deriveAesKeyBS . TE.encodeUtf8 deriveAesKeyBS :: ByteString -> AesKey deriveAesKeyBS = AesKey . blake2b where blake2b :: ByteString -> ByteString blake2b = convert @(Digest Blake2b_256) . hash aesEncrypt :: ByteString -> AesKey -> Either CryptoError ByteString aesEncrypt input (fromAESKey -> sk) = ctrCombine <$> init1 <*> pure nullIV <*> pure input where -- FIXME: return either here init1 :: Either CryptoError AES256 init1 = eitherCryptoError $ cipherInit sk aesDecrypt :: ByteString -> AesKey -> Either CryptoError ByteString aesDecrypt = aesEncrypt -- encryption/decryption is symmetric --test code let key = deriveAesKey "XmSeal" let a = aesEncrypt "PHJ10" key putStrLn $ "a:" ++ show a
2.
saltSize :: Int saltSize = 32 paramN :: Word64 paramN = 16 :: Word64 paramR :: Int paramR = 8 :: Int paramP :: Int paramP = 1 :: Int paramKeyLen :: Int paramKeyLen = 32 :: Int encrypt :: ByteString -> ByteString -> ByteString encrypt key plainData = ctrCombine ctx nullIV plainData where ctx :: AES256 ctx = throwCryptoError $ cipherInit key decrypt :: ByteString -> ByteString -> ByteString decrypt = encrypt --Scrypt KDF deriveKey :: ByteString -> ByteString -> ByteString deriveKey password salt = generate params (password) salt where params = Parameters {n = paramN, r = paramR, p = paramP, outputLength = paramKeyLen} --test code let b1 = encrypt (deriveKey "123456" "1") "ab" putStrLn $ "a:" ++ show b1
如果我的文章对你有帮助,就点一下推荐吧.(*^__^*)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步