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
复制代码

 

posted @   Gyoung  阅读(240)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示