B4J Question Help With Making A Signing Function (SHA256, Base64, Etc.)

cklester

Active Member
Licensed User
I need to create a signing function to send data to a private API.

The code in Typescript is here, and shown below:

B4X:
import * as crypto  from 'crypto';

export class AuthenticationProvider {

    public readonly publicKey: string;
    private _privateKey: Buffer;

    constructor(
        publicKey: string,
        privateKey: string,
    ) {
        this.publicKey = publicKey;
        // decode the base64 secret
        this._privateKey = new Buffer(privateKey, 'base64');
    }

    public sign(prehashString: string): string {
        // create a sha256 hmac with the secret
        const hmac = crypto.createHmac('sha256', this._privateKey);

        // hash the prehash string and base64 encode the result
        return hmac.update(prehashString).digest('base64');
    }
}



I have attempted to make the same in B4X--seems very straightforward--but I have failed to produce working code.

B4X:
Public Sub HashHmac(data As String, secret As String) As String
    Dim m As Mac
    Dim kg As KeyGenerator
    Dim Result As String
    Try
        kg.Initialize("HmacSHA256")
        kg.KeyFromBytes(secret.GetBytes("UTF8"))
        m.Initialise("HmacSHA256", kg.Key)
        m.Update(data.GetBytes("UTF8"))
        Result = su.EncodeBase64(m.Sign)
    Catch
        Result = $"HashHmac: ${LastException.Message}"$
    End Try
    Return Result
End Sub

The code above might have been derived from code elsewhere in this forum. However, it's been a while, and I've lost all track of provenance.

I'm getting errors from the API when using the above Hash function, so I'm pretty sure I'm doing it wrong.

Can anybody give me some clues or fix up the function?

Thank you!
 

oparra

Well-Known Member
Licensed User
?
 
Upvote 0

cklester

Active Member
Licensed User
?
Shrimpy seems to be a little different from Binance in that the signature is not part of the URL. I will look at that solution tomorrow and see if it gives me a clue. Thank you.
 
Upvote 0

cklester

Active Member
Licensed User
OK! I figured it out!

Based on the Shrimpy docs, the secret key has to be Base64 decoded, so instead of doing this:

B4X:
        kg.KeyFromBytes(secret.GetBytes("UTF8"))

I have to do this:

B4X:
        kg.KeyFromBytes(su.DecodeBase64(secret))

Woop! Ready to go...
 
Upvote 0
Solution
Top