2014-06-25 61 views
2

我将如何转换这种Python代码到F#“F#转换HMAC蟒成F#

message = nonce + client_id + api_key 
signature = hmac.new(API_SECRET, msg=message, digestmod=hashlib.sha256).hexdigest().upper() 

到目前为止我的代码来实现这一目标:

let message =string(nonce)+ client_id + api_key 
let signature = HMACSHA256.Create(API_secret+message) 

简单的问题是,我无法找到什么代表hexdigest() F#中的功能

此外,我是否结合了API_Secret与我已经完成的消息或必须将它们分开?

回答

4

我认为你需要somethink这样的:

let hexdigest (bytes : byte[]) = 
    let sb = System.Text.StringBuilder() 
    bytes |> Array.iter (fun b -> b.ToString("X2") |> sb.Append |> ignore) 
    string sb 

let signature = 
    use hmac = new HMACSHA256.Create(API_secret) 
    hmac.ComputeHash(message) 
    |> hexdigest 

与StringBuilder的部分是什么呢hexdigest在Python(如果我得到hexdigest右)

+0

消息是否已成为一个字节数组? – user3623025

+0

对于这种方法是的 - 你必须自己转换它 - 对于文本最简单的方法是System.Text.Encoding中的方法/类 - 例如这个编码使用UTF8的字符串:'let utf8EncodedBytes = System.Text.Encoding。 UTF8.GetBytes myString' – Carsten

+0

根据https://msdn.microsoft.com/en-us/library/9c9tf8wc(v=vs.110).aspx HMAC的创建应该是: '使用hmac = new System.Security。 Cryptography.HMACSHA256(secret)' – Infinum