Brentley_11
Brentley_11

Reputation: 75

How can I generate a v2 signature for Amazon EC2 using PHP?

I am wondering if anyone has successfully generated an EC2 v2 signature for their API using php. All examples/libraries I can find online are for v1 of the signature and that has been deprecated due to insecurities. An existing library that implements the signature generation would be appreciated too.

Upvotes: 0

Views: 2362

Answers (4)

Mark
Mark

Reputation: 812

Use constant AWSSECRET to hash the signature, NOT $AWSKEY (an unreferenced variable).

Upvotes: 0

Frank Farmer
Frank Farmer

Reputation: 39356

http://mierendo.com/software/aws_signed_query/

I believe that's V2

Upvotes: 1

mattbasta
mattbasta

Reputation: 13709

Here's some code I've written and have been using:

define("AWSKEY", "Your AWS Key");
define("AWSSECRET", "Your AWS Secret");
public function get($parameters, $host) {

    // Build out the variables
    $domain = "https://$host/";
    $parameters['AWSAccessKeyId'] = AWSKEY;
    $parameters['Timestamp'] = date('c');
    $parameters['Version'] = '2007-11-07';
    $parameters['SignatureMethod'] = 'HmacSHA256';
    $parameters['SignatureVersion'] = 2;

    // Write the signature
    $signature = "GET\n";
    $signature .= "$host\n";
    $signature .= "/\n";

    $sigparams = $parameters;

    ksort($sigparams);

    $first = true;
    foreach($sigparams as $key=>$param) {
        $signature .= (!$first ? '&' : '') . rawurlencode($key) . '=' . rawurlencode($param);
        $first = false;
    }
    $signature = hash_hmac('sha256', $signature, $AWSKEY, true);
    $signature = base64_encode($signature);
    $parameters['Signature'] = $signature;

    $url = $domain . '?';
    $first = true;
    foreach($parameters as $key=>$param) {
        $url .= (!$first ? '&' : '') . rawurlencode($key) . '=' . rawurlencode($param);
        $first = false;
    }

    $ch = curl_init(trim($url));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $output = curl_exec($ch);

    return $output;

}

Here's how you'd use it:

$params = array(
    'Action' => 'ListDomains'
);
$db->get($params, 'sdb.amazonaws.com');

This would perform a ListDomains query on SimpleDB. The function itself will return Amazon's output. For more complicated commands, (i.e.: PUT, POST, etc.) there aren't any major modifications that need to be made.

Upvotes: 0

Ólafur Waage
Ólafur Waage

Reputation: 70001

Here's a PHP Library that supports V2. I haven't tried it though.

Upvotes: 0

Related Questions