简体   繁体   English

我怎样才能在Haskell中对一个字符串的SHA256哈希进行Base64 UrlEncode?

[英]How can I Base64 UrlEncode a SHA256 Hash of a string in Haskell?

This is to create a code challenge and verifier for PKEC OAuth workflows. 这是为PKEC OAuth工作流创建代码质询和验证程序。

The following seems like it should work (uses cryptonite ): 以下似乎应该工作(使用cryptonite ):

import System.Random (newStdGen, randomRs)
import Crypto.Hash (Digest, hash)
import Crypto.Hash.Algorithms (SHA256)

x = do
    gen <- newStdGen
    codeVerifier = C.pack . take 128 $ randomRs ('0', 'z') gen
    codeChallenge = show (hash codeVerifier :: Digest SHA256)
    print codeChallenge

But alas, it does not. 但唉,事实并非如此。 So I will post the answer I finally solved after much pain and toil. 所以我会发布我经过多次痛苦和辛劳后终于解决的答案。

And the answer that OAuth workflows expect is... drum roll ~~~ 而OAuth工作流程所期望的答案是......滚动~~~

import System.Random (newStdGen, randomRs)
import Data.ByteArray.Encoding
import Crypto.Hash.Algorithms
import Crypto.Hash

-- | This is a custom sort of urlEncode that simply replaces bad characters
urlEncode :: String -> String
urlEncode [] = ""
urlEncode ('=':xs) = urlEncode xs
urlEncode ('+':xs) = '-' : urlEncode xs
urlEncode ('/':xs) = '_' : urlEncode xs
urlEncode (x : xs) = x : urlEncode xs

codeVerifier = C.pack . take 128 $ randomRs ('a', 'z') gen
codeChallenge = urlEncode . C.unpack $ (convertToBase Base64 (hashWith SHA256 codeVerifier)  :: ByteString)

The problem in the OP code is it base64 encodes a String , where as this code waits to convert the hash to a String , so you actually base64 encode the hash directly as a ByteArray . OP代码中的问题是base64对String编码,其中此代码等待将哈希值转换为String ,因此您实际上将hash64直接编码为ByteArray

Anyways, this kicked my butt, especially since the auth service I was using insisted that my error was invalid_grant . 无论如何,这踢了我的屁股,特别是因为我使用的auth服务坚持我的错误是invalid_grant It kept effing telling me that I had an invalid_grant ?! 它一直在告诉我,我有一个invalid_grant ?! Anyways, I popped a couple gray hairs over this, so figured I'd help the next unfortunate soul. 无论如何,我突然出现了几条白发,所以我想帮助下一个不幸的灵魂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM