Creating an amazon MWS signature with Delphi XE7 and Indy classes - delphi

I need to generate a signature for amazon MWS and decided to find a solution with only the components and classes which come with Delphi. Because I am using Indy for the HTTP post itself, it seemed to be a good idea to use Indy classes for the calculation of the RFC 2104-compliant HMAC.
For others, who work on amazon integration, the creation of the "Canonicalized Query String" is explained in the amazon tutorial very well: http://docs.developer.amazonservices.com/en_DE/dev_guide/DG_ClientLibraries.html
Be careful, just use #10 for line breaking, as #13#10 or #13 will fail with a wrong signature. It may also be important to add ":443" to the amazon Endpoint (Host), depending on the TIdHttp version, as explained in question #23573799.
To create a valid signature, we have to calculate a HMAC with SHA256 with the query string and the SecretKey we got from amazon after registration and then, the result has to be encoded in BASE64.
The query string is properly generated and identical to the string the amazon Scratchpad creates. But the call failed because the signature is not correct.
After some tests I realized that the signature I got from my query string is not the same as the result I got when I used PHP to generate it. The PHP result is considered as correct, as my PHP solution simply works with amazon since a long time, the Delphi result is different, which is not correct.
To make testing easier, I use '1234567890' as value for the query string and 'ABCDEFG' as replacement for the SecretKey. When the result I get with Delphi is the same as the result I get with PHP, the problem should be solved, I believe.
Here is how I get the correct result with PHP:
echo base64_encode(hash_hmac('sha256', '1234567890', 'ABCDEFG', TRUE));
This shows a result of
aRGlc3RY1pKmKX0hvorkVKNcPigiJX2rksqXzlAeCLg=
The following Delphi XE7 code returns the wrong result, while using the indy version that comes with Delphi XE7:
uses
  IdHash, IdHashSHA, IdHMACSHA1, IdSSLOpenSSL, IdGlobal, IdCoderMIME;
function GenerateSignature(const AData, AKey: string): string;
var
   AHMAC: TIdBytes;
begin
     IdSSLOpenSSL.LoadOpenSSLLibrary;
     With TIdHMACSHA256.Create do
      try
         Key:= ToBytes(AKey, IndyTextEncoding_UTF16LE);
         AHMAC:= HashValue(ToBytes(AData, IndyTextEncoding_UTF16LE));
         Result:= TIdEncoderMIME.EncodeBytes(AHMAC);
      finally
         Free;
      end;
end;
Here the result, which is shown in a Memo with
Memo.Lines.Text:= GenerateSignature('1234567890', 'ABCDEFG');
is:
jg6Oddxvv57fFdcCPXrqGWB9YD5rSvtmGnZWL0X+y0Y=
I believe the problem has something to do with the encodings, so I have done some research around that. As the amazon tutorial (link see above) tells, amazon expects a utf8 encoding.
As the Indy function "ToBytes" expect a string, which is a UnicodeString in my Delphi version, I quit testing with other string types as UTF8String for parameters or variables, but I just do not know where utf8 should come into place. Also I do not know if the encodings I use in the code above are the correct ones.
I choose UTF16LE because UnicodeString is utf16 encoded (see http://docwiki.embarcadero.com/RADStudio/Seattle/en/String_Types_(Delphi) for details) and LE (Little-Endian) is most commonly used on modern machines. Also the TEncodings of Delphi itself there is "Unicode" and "BigEndianUnicode", so "Unicode" seems to be LE and some kind of "standard" Unicode.
Of course I tested to use IndyTextEncoding_UTF8 instead of IndyTextEncoding_UTF16LE in the code above, but it does not work anyway.
Because
TIdEncoderMIME.EncodeBytes(AHMAC);
is writing the TidBytes to a Stream first and then reading it all with 8bit encoding, this could be a source of problem also, so I also tested with
Result:= BytesToString(AHMAC, IndyTextEncoding_UTF16LE);
Result:= TIdEncoderMIME.EncodeString(Result, IndyTextEncoding_UTF16LE);
but the result is the same.
If you like to see the main code for creating the request, here it is:
function TgboAmazon.MwsRequest(const AFolder, AVersion: string;
const AParams: TStringList; const AEndPoint: string): string;
var
i: Integer;
SL: TStringList;
AMethod, AHost, AURI, ARequest, AStrToSign, APath, ASignature: string;
AKey, AValue, AQuery: string;
AHTTP: TIdHTTP;
AStream, AResultStream: TStringStream;
begin
AMethod:= 'POST';
AHost:= AEndPoint;
AURI:= '/' + AFolder + '/' + AVersion;
AQuery:= '';
SL:= TStringList.Create;
try
SL.Assign(AParams);
SL.Values['AWSAccessKeyId']:= FAWSAccessKeyId;
SL.Values['SellerId']:= FSellerId;
FOR i:=0 TO FMarketplaceIds.Count-1 DO
begin
SL.Values['MarketplaceId.Id.' + IntToStr(i+1)]:= FMarketplaceIds[i];
end;
SL.Values['Timestamp']:= GenerateTimeStamp(Now);
SL.Values['SignatureMethod']:= 'HmacSHA256';
SL.Values['SignatureVersion']:= '2';
SL.Values['Version']:= AVersion;
FOR i:=0 TO SL.Count-1 DO
begin
AKey:= UrlEncode(SL.Names[i]);
AValue:= UrlEncode(SL.ValueFromIndex[i]);
SL[i]:= AKey + '=' + AValue;
end;
SortList(SL);
SL.Delimiter:= '&';
AQuery:= SL.DelimitedText;
AStrToSign:= AMethod + #10 + AHost + #10 + AURI + #10 + AQuery;
TgboUtil.ShowMessage(AStrToSign);
ASignature:= GenerateSignature(AStrToSign, FAWSSecretKey);
TgboUtil.ShowMessage(ASignature);
APath:= 'https://' + AHost + AURI + '?' + AQuery + '&Signature=' + Urlencode(ASignature);
TgboUtil.ShowMessage(APath);
finally
SL.Free;
end;
AHTTP:= TIdHTTP.Create(nil);
try
AHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(AHTTP);
AHTTP.Request.ContentType:= 'text/xml';
AHTTP.Request.Connection:= 'Close';
AHTTP.Request.CustomHeaders.Add('x-amazon-user-agent: MyApp/1.0 (Language=Delphi/XE7)');
AHTTP.HTTPOptions:= AHTTP.HTTPOptions + [hoKeepOrigProtocol];
AHTTP.ProtocolVersion:= pv1_0;
AStream:= TStringStream.Create;
AResultStream:= TStringStream.Create;
try
AHTTP.Post(APath, AStream, AResultStream);
Result:= AResultStream.DataString;
ShowMessage(Result);
finally
AStream.Free;
AResultStream.Free;
end;
finally
AHTTP.Free;
end;
end;
Urlencode and GenerateTimestamp are my own functions and they do what the name promises, SortList is my own procedure which sorts the stringlist in a byte order as requested by amazon, TgboUtil.ShowMessage is my own ShowMessage alternative which shows the complete message with all characters and is used for debugging only. The http protocol is 1.0 for testing only, because I got a 403 (permission denied) as HTTP return earlier. I just wanted to exclude this as problem as the indy documentation said, that protocol version 1.1 is considered incomplete because of problematic server answers.
There are several posts regarding the amazon mws topic here, but that specific problem seems to be new.
This question here may help someone who just not have come so far, but also I hope that someone can provide a solution to just get the same signature value in Delphi as I got with PHP.
Thank you in advance.

Using the latest SVN snapshot of Indy 10, I am not able to reproduce your signature problem. When using UTF-8, your example key+value data produces the same result in Delphi as the PHP output. So, your GenerateSignature() function is fine, provided that:
you use IndyTextEncoding_UTF8 instead of IndyTextEncoding_UTF16LE.
you make sure that AData and AKey contain valid input data.
Also, you should make sure that TIdHashSHA256.IsAvailable returns true, otherwise TIdHashHMACSHA256.HashValue() will fail.
this could happen, for instance, if OpenSSL fails to load.
Try this instead:
function GenerateSignature(const AData, AKey: string): string;
var
AHMAC: TIdBytes;
begin
IdSSLOpenSSL.LoadOpenSSLLibrary;
if not TIdHashSHA256.IsAvailable then
raise Exception.Create('SHA-256 hashing is not available!');
with TIdHMACSHA256.Create do
try
Key := IndyTextEncoding_UTF8.GetBytes(AKey);
AHMAC := HashValue(IndyTextEncoding_UTF8.GetBytes(AData));
finally
Free;
end;
Result := TIdEncoderMIME.EncodeBytes(AHMAC);
end;
That being said, there are quite a few problems with your MwsRequest() function:
you are leaking the TIdSSLIOHandlerSocketOpenSSL object. You are not assigning an Owner to it, and TIdHTTP does not take ownership when assigned to its IOHandler property. In fact, assigning the IOHanlder is actually optional in your example, see New HTTPS functionality for TIdHTTP for why.
you are setting AHTTP.Request.ContentType to the wrong media type. You are not sending XML data, so don't set the media type to 'text/xml'. In this situation, you need to set it to 'application/x-www-form-urlencoded' instead.
when calling AHTTP.Post(), your AStream stream is empty, so you are not actually posting any data to the server. You are putting your AQuery data in the query string of the URL itself, but it actually belongs in AStream instead. If you want to sent the data in the URL query string, you have to use TIdHTTP.Get() instead of TIdHTTP.Post(), and change your AMethod value to 'GET' instead of 'POST'.
you are using the version of TIdHTTP.Post() that fills an output TStream. You are using a TStringStream to convert the response to a String without any regard to the actual charset used by the response data. Since you are not specifying any TEncoding object in the TStringStream constructor, it will use TEncoding.Default for decoding, which may not (and likely will not) match the response's actual charset. You should instead use the other version of Post() that returns a String so TIdHTTP can decode the response data based on the actual charset reported by the HTTPS server.
Try something more like this instead:
function TgboAmazon.MwsRequest(const AFolder, AVersion: string;
const AParams: TStringList; const AEndPoint: string): string;
var
i: Integer;
SL: TStringList;
AMethod, AHost, AURI, AQuery, AStrToSign, APath, ASignature: string;
AHTTP: TIdHTTP;
begin
AMethod := 'POST';
AHost := AEndPoint;
AURI := '/' + AFolder + '/' + AVersion;
AQuery := '';
SL := TStringList.Create;
try
SL.Assign(AParams);
SL.Values['AWSAccessKeyId'] := FAWSAccessKeyId;
SL.Values['SellerId'] := FSellerId;
for i := 0 to FMarketplaceIds.Count-1 do
begin
SL.Values['MarketplaceId.Id.' + IntToStr(i+1)] := FMarketplaceIds[i];
end;
SL.Values['Timestamp'] := GenerateTimeStamp(Now);
SL.Values['SignatureMethod'] := 'HmacSHA256';
SL.Values['SignatureVersion'] := '2';
SL.Values['Version'] := AVersion;
SL.Values['Signature'] := '';
SortList(SL);
for i := 0 to SL.Count-1 do
SL[i] := UrlEncode(SL.Names[i]) + '=' + UrlEncode(SL.ValueFromIndex[i]);
SL.Delimiter := '&';
SL.QuoteChar := #0;
SL.StrictDelimiter := True;
AQuery := SL.DelimitedText;
finally
SL.Free;
end;
AStrToSign := AMethod + #10 + Lowercase(AHost) + #10 + AURI + #10 + AQuery;
TgboUtil.ShowMessage(AStrToSign);
ASignature := GenerateSignature(AStrToSign, FAWSSecretKey);
TgboUtil.ShowMessage(ASignature);
APath := 'https://' + AHost + AURI;
TgboUtil.ShowMessage(APath);
AHTTP := TIdHTTP.Create(nil);
try
// this is actually optional in this example...
AHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(AHTTP);
AHTTP.Request.ContentType := 'application/x-www-form-urlencoded';
AHTTP.Request.Connection := 'close';
AHTTP.Request.UserAgent := 'MyApp/1.0 (Language=Delphi/XE7)';
AHTTP.Request.CustomHeaders.Values['x-amazon-user-agent'] := 'MyApp/1.0 (Language=Delphi/XE7)';
AHTTP.HTTPOptions := AHTTP.HTTPOptions + [hoKeepOrigProtocol];
AHTTP.ProtocolVersion := pv1_0;
AStream := TStringStream.Create(AQuery + '&Signature=' + Urlencode(ASignature);
try
Result := AHTTP.Post(APath, AStream);
ShowMessage(Result);
finally
AStream.Free;
end;
finally
AHTTP.Free;
end;
end;
However, since the response is documented as being XML, it would be better to return the response to the caller as a TStream (not using TStringStream, though) or TBytes instead of as a String. That way, instead of Indy decoding the bytes, let your XML parser decode the raw bytes on its own. XML has its own charset rules that are separate from HTTP, so let the XML parser do its job for you:
procedure TgboAmazon.MwsRequest(...; Response: TStream);
var
...
begin
...
AHTTP.Post(APath, AStream, Response);
...
end;

Related

How to set body data indy HTTPS post

So I've looked around, and the only question describing my problem is 6 years old with 0 answers, so I guess I will try again.
I am using delphi 2009 with Indy10.
I am trying to post JSON to an api using HTTPS.
Instance.FHTTP := TIdHTTP.Create;
Instance.FHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(Instance.FHTTP);
{$IFDEF DEBUG}
Instance.FHTTP.ProxyParams.ProxyPort := 8888;
Instance.FHTTP.ProxyParams.ProxyServer := '127.0.0.1';
{$ENDIF}
Instance.FHTTP.Request.ContentType := 'application/json';
Instance.FAccessToken := Instance.FHTTP.Post('https://somedomain.com/api/endpoint', '{JSONName: JSONValue }' );
I have seen many answers suggesting that the JSON payload should be given as a string param in the TidHTTP.Postmethod, but when i try that, it expects a filepath, and throws an error saying:
'Cannot open file "[path to project{JSONName:JSONValue }]". The specified file was not found'.
If i add my JSON to a TStringList and add give that as a parameter, it simply adds the JSON to the header of the request.
Any help is greatly appreciated.
The Post overload that takes a second string indeed interprets it as a filename:
function Post(AURL: string; const ASourceFile: String): string; overload;
That's why this doesn't work. You need to instead use the overload that takes a TStream:
function Post(AURL: string; ASource: TStream): string; overload;
You can put your JSON in a TStringStream:
StringStream := TStringStream.Create('{JSONName: JSONValue }', TEncoding.UTF8);
try
Instance.FAccessToken := Instance.FHTTP.Post('https://somedomain.com/api/endpoint', StringStream);
finally
StringStream.Free;
end;

Create Google-Maps-API signature with Delphi

I would like to create signatures for my maps-for-work clientid. I need to get the geolocation-api running with my clientid. The API is called for example like this:
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&client=gme-myPersonalclientid&signature=HereIsMyProblem
I call this link from my Delphi application.
I tried to transfer phyton/java/c# from the official helpsite (https://developers.google.com/maps/documentation/static-maps/get-api-key?hl=en) to Delphi but I am still missing something.
function TMgrGoogleMap.SignUrl(AUrl: String): String;
Var
CryptoKey: String;
Signature: String;
HMac: TIdHMACSHA1;
CryptoIDByte: TBytes;
SignatureHash: TidBytes;
begin
// IdSSLOpenSSL.LoadOpenSSLLibrary; // not sure if needed, think not
CryptoKey := 'ARandomKryptoKeyfY1XbqTib1QlY=';
CryptoIDByte := TNetEncoding.Base64.DecodeStringToBytes(CryptoKey);
HMac := TIdHMACSHA1.Create;
HMac.Key := TIdBytes(CryptoIDByte);
SignatureHash := HMac.HashValue(TidBytes(AUrl));
Signature := TNetEncoding.Base64.EncodeBytesToString(SignatureHash);
Result := AUrl + '&signature=' + Signature;
end;
As Google-Help code-examples tell, I first decode my cryptokey with Base64, then I create a hash-value with SHA-1 with the encoded cryptokey and the url.
Afterwards I encode it again with Base64 but the result is unfortunately another then the onlinetest https://m4b-url-signer.appspot.com/ gives.
What am I missing? Thanks for every answer in advance.

UDPSocketClient.Receiveln doesn't Proceed all Incoming Data

I'm using Delphi XE4, with UDPSocketClient I send a Request to the Server.
The Request is successful, but the responce from the Server is always about 200 bytes.
It should be about 1000 bytes.
I have no clue why?! There is no EOL break or something like that.
Is it possible to read in Chunks?
procedure TForm1.SendCommand(const Pass, ACommand: string);
var
Cmd: string;
begin
if UDPSocketClient.Connected then
begin
Cmd := Pass + ' ' + ACommand;
UDPSocketClient.Sendln(AnsiString(Cmd));
Memo1.Lines.Add('');
Memo1.Lines.Add('######################');
Memo1.Lines.Add(ACommand);
Memo1.Lines.Add('######################');
Memo1.Lines.Add('');
end;
end;
procedure TForm1.BtnSendCmdClick(Sender: TObject);
var
Buff: AnsiString;
received: string;
begin
if Assigned(CurrentServer) and (CmdEdit.Text <> '') and
(CmdEdit.Text <> CmdEditPlaceHolder) then
begin
SendCommand(CurrentServer.Password, CmdEdit.Text);
end;
try
received := String(UDPSocketClient.Receiveln(Buff));
Memo1.Lines.Add(received);
finally
CmdEdit.SetFocus;
end;
I assume you're using TUDPSocket.
The parameter for ReceiveLn is the delimiter string to search for. You're passing it Buff which is an empty string, so the behaviour is likely to be undefined.
So, now I have an approach to a solution.
When i send the Command to the Server, there are two possibilitys to receive the Data:
The Incoming UDP Package is less than 200bytes, everything will be correct.
If the Incoming UDP Package reached the 1.3kb, then there are two udp packages in the socket buffer. But i can't get the Packages to my Application.

HTTP.post versus downloadURL using Delphi XE2

I am trying to use the same procedure for two types of downloads. both are working.
I would like to use TDownloadURL or HTTP.Post on both, but cannot determine how. Which method and how to do this? Thank you.
First operation --
procedure TfrmMain.get1Click(Sender: TObject);
var
json: string;
lHTTP: TIdHTTP;
lParamList: TStringList;
result:string;
begin
json := CRLF +
'{' + CRLF +
' "resource_id": "391792b5-9c0a-48a1-918f-2ee63caa1c54",' + CRLF +
' "filters": {' + CRLF +
' "provider_id": 393303' + CRLF +
' }' + CRLF +
'}';
lParamList := TStringList.Create;
try
lParamList.Add('somename='+json);
lHTTP := TIdHTTP.Create(nil);
try
Result := lHTTP.Post('http://hub.Healthdata.gov/api/action/datastore_search', lParamList);
finally
lHTTP.Free;
end;
finally
lParamList.Free;
end;
end;
Second operation --
procedure TfrmMain.get2Click(Sender: TObject);
var
dl: TDownloadURL;
url:string;
begin
url:='http://api.census.gov/data/2010/sf1?key=KEY&get=P0010001,NAME&for=state:*';
dl := TDownloadURL.Create(self);
try
dl.URL := url;
dl.FileName := execpath+'api1.txt'; dl.ExecuteTarget(nil); dl.Free;
except
dl.Free;
end;
end;
TDownloadURL uses the GET HTTP method. TIdHTTP.Post obviously uses the POST method. In general, neither is appropriate for use in place of the other. That's why both methods exist in the first place.
A POST request can include all the information that a GET request does, plus more, which makes it seem like it should be able to do everything GET can do, plus more. However, servers are not required to (and should not be expected to) handle POST requests the same way they do GET.
As the one writing the HTTP client, you're not really in control of the situation. The server dictates which methods it will honor. Clients need to either do what's expected of them or be denied access.
The Indy components support both methods, so if you just want to make your POST code and your GET code look similar, then you can replace TDownloadURL with TIdHTTP.Get.

Delphi: Using Google URL Shortener with IdHTTP - 400 Bad Request

I'm trying to access the URL Shortener ( http://goo.gl/ ) via its API from within Delphi.
However, the only result I get is: HTTP/1.0 400 Bad Request (reason: parseError)
Here is my code (on a form with a Button1, Memo1 and IdHTTP1 that has IdSSLIOHandlerSocketOpenSSL1 as its IOHandler. I got the necessary 32-bit OpenSSL DLLs from http://indy.fulgan.com/SSL/ and put them in the .exe's directory):
procedure TFrmMain.Button1Click(Sender: TObject);
var html, actionurl: String;
makeshort: TStringList;
begin
try
makeshort := TStringList.Create;
actionurl := 'https://www.googleapis.com/urlshortener/v1/url';
makeshort.Add('{"longUrl": "http://slashdot.org/stories"}');
IdHttp1.Request.ContentType := 'application/json';
//IdHTTP1.Request.ContentEncoding := 'UTF-8'; //Using this gives error 415
html := IdHTTP1.Post(actionurl, makeshort);
memo1.lines.add(idHTTP1.response.ResponseText);
except on e: EIdHTTPProtocolException do
begin
memo1.lines.add(idHTTP1.response.ResponseText);
memo1.lines.add(e.ErrorMessage);
end;
end;
memo1.Lines.add(html);
makeshort.Free;
end;
Update: I have left off my API key in this example (should usually work well without one for a few tries), but if you want to try it with your own, you can substitute the actionurl string with
'https://www.googleapis.com/urlshortener/v1/url?key=<yourapikey>';
The ParseError message leads me to believe that there might be something wrong with the encoding of the longurl when it gets posted but I wouldn't know what to change.
I've been fuzzing over this for quite a while now and I'm sure the mistake is right before my eyes - I'm just not seeing it right now.
Any help is therefore greatly appreciated!
Thanks!
As you discovered, the TStrings overloaded version of the TIdHTTP.Post() method is the wrong method to use. It sends an application/x-www-form-urlencoded formatted request, which is not appropriate for a JSON formatted request. You have to use the TStream overloaded version of the TIdHTTP.Post() method instead`, eg:
procedure TFrmMain.Button1Click(Sender: TObject);
var
html, actionurl: String;
makeshort: TMemoryStream;
begin
try
makeshort := TMemoryStream.Create;
try
actionurl := 'https://www.googleapis.com/urlshortener/v1/url';
WriteStringToStream(makeshort, '{"longUrl": "http://slashdot.org/stories"}', IndyUTF8Encoding);
makeshort.Position := 0;
IdHTTP1.Request.ContentType := 'application/json';
IdHTTP1.Request.Charset := 'utf-8';
html := IdHTTP1.Post(actionurl, makeshort);
finally
makeshort.Free;
end;
Memo1.Lines.Add(IdHTTP1.Response.ResponseText);
Memo1.Lines.Add(html);
except
on e: Exception do
begin
Memo1.Lines.Add(e.Message);
if e is EIdHTTPProtocolException then
Memo1.lines.Add(EIdHTTPProtocolException(e).ErrorMessage);
end;
end;
end;
From the URL shortener API docs:
Every request your application sends to the Google URL Shortener API
needs to identify your application to Google. There are two ways to
identify your application: using an OAuth 2.0 token (which also
authorizes the request) and/or using the application's API key.
Your example does not contain code for OAuth or API key authentication.
To authenticate with an API key, the docs are clear:
After you have an API key, your application can append the query
parameter key=yourAPIKey to all request URLs.

Resources