Search code examples
c#cryptographybouncycastlewalmart-api

How to authenticate using private key - Walmart Affiliate


I'm trying to use the Walmart Affiliate API, which uses a public/private token for authentication. I'm having trouble figuring out what I'm missing from the steps provided.

I currently have a DelegatingHandler to add the Headers values needed. I'm using BouncyCastle to help in the private token signing and this is what I have currently.

    public static string Generate(string version, string consumerId, string timestamp)
    {
        // Canonicalize the headers, following after the java code in the docs.
        string[] canonicalStrings = Canonicalize(version, consumerId, timestamp);

        // Read the file with the password protected private key
        StreamReader stream= new StreamReader(@"..\key");
        PasswordFinder finder = new PasswordFinder("1234");

        // Actually get the private key
        PemReader pemReader= new PemReader(stream, finder);
        AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
        RSAParameters rsa = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
        
        // Create the RSA Provider and import the private key
        RSACryptoServiceProvider provider = new RSACryptoServiceProvider(2048);
        provider.ImportParameters(rsa);

        // Sign the canonicalized data
        byte[] signedData = provider.SignData(Encoding.UTF8.GetBytes(canonicalStrings[1]), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

        // Convert the bytes to a base-64 string.
        return Convert.ToBase64String(signedData);
    }

    private static string[] Canonicalize(string version, string consumerId, string timestamp)
    {
        // Follow after the java code, which just orders the keys/values.
        StringBuilder keyBuilder = new StringBuilder();
        StringBuilder valueBuilder = new StringBuilder();
        SortedDictionary<string, string> dictionary = new SortedDictionary<string, string>() { { Constants.HEADER_COMSUMER_ID, consumerId }, { Constants.HEADER_TIMESTAMP, timestamp }, { Constants.HEADER_KEY_VERSION, version } };

        foreach (string key in dictionary.Keys)
        {
            keyBuilder.Append($"{key.Trim()};");
            valueBuilder.AppendLine($"{dictionary[key].Trim()}");
        }

        return new string[] {keyBuilder.ToString(), valueBuilder.ToString()};
    }

This is called via my DelegatingHandler by:

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        string version = _walmartConfig.CurrentValue.Version; // Get Version from config
        string consumerId = _walmartConfig.CurrentValue.StageConsumerId; // Get ConsumerID from config
        string timestamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
        string signature = Generator.Generate(version, consumerId, timestamp); // Generate signature

        request.Headers.Add(Constants.HEADER_KEY_VERSION, version);
        request.Headers.Add(Constants.HEADER_COMSUMER_ID, consumerId);
        request.Headers.Add(Constants.HEADER_TIMESTAMP, timestamp);
        request.Headers.Add(Constants.HEADER_SIGNATURE, signature);
        return base.SendAsync(request, cancellationToken);
    }

It's kicked off via an example call as mentioned in the docs:

        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://developer.api.walmart.com/api-proxy/service/affil/product/v2/taxonomy"))
        {
            HttpResponseMessage response = await _client.SendAsync(request); // This returns HTTP 401.

            return response.Content.ToString();
        }

My private key was generated following the steps mentioned here for Windows, but I exported the private key using the PuTTy menu item: Conversions -> Export OpenSSH key

That private key file looks something like:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,F014B20CAD95382A

0CE3...
-----END RSA PRIVATE KEY-----

I think I'm following the guide correctly, but I am still getting HTTP 401's from their API. Can anybody figure out what I did wrong?


Solution

  • I ended up solving it by mainly using the OpenSSL key creation through a unix terminal, but here's the final product if it helps anybody else.

    Usage:

    string signature = Signer.SignData(Signer.Canonicalize(version, consumerId, timestamp)[1], _keyManager.Key);
    

    _keyManager.Key is found by using BouncyCastle to read the password protected private key.

    StreamReader sr = File.OpenText("c:\key.pem");
    PemReader pr = new PemReader(sr, new PasswordFinder("123"));
    RsaPrivateCrtKeyParameters keyPair = pr.ReadObject() as RsaPrivateCrtKeyParameters;
    return DotNetUtilities.ToRSAParameters(keyPair);
    

    Finally the Signer.SignData implementation.

    public static string SignData(string message, RSAParameters privateKey)
    {
        byte[] signedBytes;
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        {
            byte[] originalBytes = Encoding.UTF8.GetBytes(message);
    
            try
            {
                rsa.ImportParameters(privateKey);
    
                signedBytes = rsa.SignData(originalBytes, CryptoConfig.MapNameToOID("SHA256"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
            finally
            {
                rsa.PersistKeyInCsp = false;
                }
        }
    
        return Convert.ToBase64String(signedBytes);
    }
    

    To confirm it works I used the public key to verify. The fetching of the public key is similar to the private.

    public static bool Verify(string originalData, string base64SignedData, RSAParameters publicKey)
    {
        bool success = false;
        byte[] signedBytes = Convert.FromBase64String(base64SignedData);
        byte[] bytesToVerify = Encoding.UTF8.GetBytes(originalData);
    
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        {
            try
            {
                rsa.ImportParameters(publicKey);
                SHA256 sha256 = new SHA256Managed();
    
                byte[] hashedData = sha256.ComputeHash(signedBytes);
    
                success = rsa.VerifyData(bytesToVerify, CryptoConfig.MapNameToOID("SHA256"), signedBytes);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
            finally
            {
                rsa.PersistKeyInCsp = false;
            }
        }
    
        return success;
    }
    

    Putting it all together as a test:

    public void SignTest()
    {
        // Arrange
        string version = "1";
        string consumerId = "8644d500-eyue-47gh-9b2b-54d5a4b9d45t";
        string timestamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
    
        StreamReader sr = File.OpenText(@"C:\privateKey.pem");
        PemReader pr = new PemReader(sr, new PasswordFinder("123"));
        RsaPrivateCrtKeyParameters keyPair = (RsaPrivateCrtKeyParameters)pr.ReadObject();
        RSAParameters rsaPrivateParameters = DotNetUtilities.ToRSAParameters(keyPair);
    
        StreamReader sr2 = File.OpenText(@"C:\publicKey.pem");
        PemReader pr2 = new PemReader(sr2, new PasswordFinder("123"));
        var keyPair2 = pr2.ReadObject();
        RSAParameters rsaPublicParameters = DotNetUtilities.ToRSAParameters((RsaKeyParameters)keyPair2);
    
        string[] canonicalForm = Signer.Canonicalize(version, consumerId, timestamp);
        
        // Act
        string signedData = Signer.SignData(canonicalForm[1], rsaPrivateParameters);
        bool validated = Signer.Verify(canonicalForm[1], signedData, rsaPublicParameters);
    
        // Assert
        Assert.True(validated);
    }