简体   繁体   中英

Convert C# API Request to PHP

I need connect to an external API and the provider has only supplied example in C#.

Here is the C# code to generate a auth token.

public static void Main()
{
    string json = @"{
      Agent : "XXX",
      Group: "XXXXXXX"
    }";

    string publicKey = "XXXXXXXXXXXXXXXXXX"

    byte[] agentBytes = Encoding.UTF8.GetBytes(json);

    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

    var rsa2Params = rsa.ExportParameters(false);
    rsa2Params.Modulus = Convert.FromBase64String(publicKey);
    rsa.ImportParameters(rsa2Params);

    byte[] hashValue = rsa.Encrypt(agentBytes, true);

    string output = Convert.ToBase64String(hashValue);
    Console.WriteLine(output);
}

I have trued with the RSA.php class

$rsa = new phpseclib\Crypt\RSA;
$keys = $rsa->createKey();

$json = json_encode([
   'Agent' => 'XXX',
   'Group' => 'XXXXXXX'
]);

$rsa->loadKey($keys['privatekey']);

$output = base64_encode($rsa->encrypt($json));

The output gives me a Auth Key to use in the header request. I hope I am on the right track, I get a API response saying the "Agent not found"

This was the C# conversion to PHP

$rsa = new \phpseclib\Crypt\RSA();

$json = json_encode([
   'Agent' => 'XXX',
   'Group' => 'XXXXXX'
]);

$publicKey = 'XXXXXXXXXXXXXXXXXX';
$exponent = 'AQAB';

$public = [
    'n' => new \phpseclib\Math\BigInteger(base64_decode($publicKey), 256),
    'e' => new \phpseclib\Math\BigInteger(base64_decode($exponent), 256),
];

$rsa->loadKey($public);

$token = base64_encode($rsa->encrypt($json));

The PHP's example is inconsistent to me:

you have:

$json = json_encode([
   'Agent' => 'XXX',
   'Group:' => 'XXXXXXX'
]);

there is colon : for Group but there is no colon for Agent, you probably should have a colon for both or not have it at all.

also there are in C# example multiple quotes (I don't know C#) but perhaps the right JSON for PHP would be:

$json = json_encode([
   'Agent' => '"XXX"',
   'Group' => '"XXXXXXX"'
]);

or

$json = json_encode([
   'Agent:' => '"XXX"',
   'Group:' => '"XXXXXXX"'
]);

most likely working:

$json = json_encode([
   'Agent' => 'XXX',
   'Group' => 'XXXXXXX'
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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