How to authenticate using C# when making calls to 2checkout API - c#

I am trying to make a call to 2checkout API. According to their documentation first I need to authenticate. All example code on their website is written in PHP.
When I try the same using C# I am getting "Hash signature could not be authenticated" message from the server.
Here is code-snipped from my code:
Encoding encoding = Encoding.UTF8;
string vendorCode = //My vendor code
string secretKey = //My secret key
byte[] secretBytes = encoding.GetBytes(secretKey);
date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string input = vendorCode.Length.ToString() + vendorCode + date.Length.ToString() + date;
using (HMACMD5 keyedHash = new HMACMD5(secretBytes))
{
byte[] hashedBytes = keyedHash.ComputeHash(encoding.GetBytes(input));
string hash = Convert.ToBase64String(hashedBytes);
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiUrl +
requestString))
{
request.Headers.Add("accept", "application/json");
string headerValue = "code=\"" + vendorCode + "\" date=\"" + date + "\" hash=\"" + hash + "\"";
request.Headers.Add("X-Avangate-Authentication", headerValue);
HttpResponseMessage httpResponse = await httpClient.SendAsync(request);
}
}
I am not sure what I am doing wrong. Is it the hash algorithm that I use or it is the text encoding?
I tried several variants but without any success.
I will be very grateful if someone helps me with this.

The below code block works for me. Code slightly modified as per needs on basis of the documentation https://verifone.cloud/docs/2checkout/API-Integration/Webhooks/06Instant_Payment_Notification_%2528IPN%2529/IPN-code-samples#c__0023__00a0
string secretKey = "MYSECRETKEY";
string VendorCode = "MYVENDORCODE";
string requestDateTime = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
string plaintext = VendorCode.Length + VendorCode + requestDateTime.Length + requestDateTime;
using(HMACMD5 hmac = new HMACMD5(Encoding.ASCII.GetBytes(secretKey)))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(plaintext));
string signatureHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.avangate.com/rest/6.0/") })
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-Avangate-Authentication", $"code='{VendorCode}' date='{requestDateTime}' hash='{signatureHash}'");
// Make your requests to desired Api
}
}

Related

I am trying to get request token from Twitter api using c#, but getting 400 bad request error

I'm trying to get request token from Twitter oauth/request_token API for the user based further authentication. The code return 400 bad request error. I know there could be a small glitch in the request which I am not able to catch. I have tried to match everything according to the documentation but somewhere something is missing. Any leads would be highly appreciable.
public void get_Oauth_token()
{
string oauth_nonce;
string oauth_callback;
string oauth_signature_method;
string oauth_timestamp;
string oauth_consumer_key;
string oauth_signature;
string oauth_version;
string req_url;
//set values to variables
var dt = DateTime.Now;
var ticks = dt.Ticks;
var seconds = ticks / TimeSpan.TicksPerSecond;
long unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
oauth_timestamp = unixTimestamp.ToString();
oauth_callback = "http://127.0.0.1:4200/home";
oauth_nonce = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 16).ToString(); //random string
oauth_signature_method = "HMAC-SHA1";
oauth_consumer_key = "xxxx";
oauth_version = "1.0";
req_url = "https://api.twitter.com/oauth/request_token";
oauth_signature = create_auth_Signature_Task(oauth_nonce, oauth_callback, oauth_signature_method, oauth_timestamp, oauth_consumer_key, oauth_version, req_url);
///action
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(req_url);
request.Method = "POST";
request.UserAgent = "themattharris' HTTP Client";
request.Host = "api.twitter.com";
request.Headers.Add(HttpRequestHeader.Authorization, "OAuth oauth_callback = \"" + Uri.EscapeDataString(oauth_callback) + "\"" + ",oauth_consumer_key = \"" + oauth_consumer_key + "\",oauth_nonce = " + "\"" + oauth_nonce + "\", oauth_signature = \"" + oauth_signature + "\", oauth_signature_method = \"HMAC-SHA1\", oauth_timestamp = \"" + oauth_timestamp + "\", oauth_version = \"1.0\"");
//WebResponse response = await request.GetResponseAsync();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream str = response.GetResponseStream();
StreamReader reader = new StreamReader(str);
dynamic resp = reader.ReadToEndAsync();
}
private string create_auth_Signature_Task(string oauth_nonce, string oauth_callback,
string oauth_signature_method, string oauth_timestamp, string oauth_consumer_key, string oauth_version, string req_url)
{
string oauth_nonce_enc = Uri.EscapeDataString(oauth_nonce);
string oauth_callback_enc = Uri.EscapeDataString(oauth_callback);
string oauth_signature_method_enc = Uri.EscapeDataString(oauth_signature_method);
string oauth_timestamp_enc = Uri.EscapeDataString(oauth_timestamp);
string oauth_consumer_key_enc = Uri.EscapeDataString(oauth_consumer_key);
string oauth_version_enc = Uri.EscapeDataString(oauth_version);
string req_url_enc = Uri.EscapeDataString(req_url);
string secret = Uri.EscapeDataString("xxxx") + "&";
string signature_base = "POST&" + req_url_enc + "&" + Uri.EscapeDataString("oauth_consumer_key=" + oauth_consumer_key_enc + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method_enc + "&oauth_timestamp=" + oauth_timestamp_enc + "&oauth_version=" + oauth_version_enc);
return ShaHash(signature_base, secret);
}
private string ShaHash(string value, string key)
{
using (var hmac = new HMACSHA1(Encoding.UTF32.GetBytes(key)))
{
return Convert.ToBase64String(hmac.ComputeHash(Encoding.ASCII.GetBytes(value)));//ByteToString(hmac.ComputeHash(Encoding.UTF32.GetBytes(value)));
}
}
instead of HttpWebRequest, you could use HttpClient which support async request.
Try to use this code block
public async void GetToken()
{
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token");
string oauth_consumer_key = "<consumer key>";
string oauth_consumer_secret = "<consumer secret>";
string url = "https://api.twitter.com/oauth2/token?oauth_consumer_key=" + oauth_consumer_key + "&oauth_consumer_secret=" + oauth_consumer_secret;
var customerInfo = Convert.ToBase64String(new UTF8Encoding()
.GetBytes(oauth_consumer_key + ":" + oauth_consumer_secret));
request.Headers.Add("Authorization", "Basic " + customerInfo);
request.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8,
"application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.SendAsync(request);
string json = await response.Content.ReadAsStringAsync();
var serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(json);
}
P.S Keep in mind that instead of creating a new instance of HttpClient for each execution you should share a single instance of HttpClient for the entire lifetime of the application otherwise you may encounter this error
Unable to connect to the remote server
System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted.
More about this here
Just use oauth-dotnetcore https://github.com/rhargreaves/oauth-dotnetcore. It would help with creating your Oauth 1.0a authorization headers.
var oauthClient = new OAuthRequest
{
Method = "POST",
Type = OAuthRequestType.RequestToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
RequestUrl = "https://api.twitter.com/oauth/request_token",
Version = "1.0a",
Realm = "twitter.com",
CallbackUrl = callbackUrl
};
Then you can get the authourization header like this:
string auth = oauthClient.GetAuthorizationHeader();
client.DefaultRequestHeaders.Add("Authorization", auth);
then use whatever client to make the http request.

Create Table in Azure using REST API

Has anyone tried creating a table inside a storage account using REST API? I can do it without an issue if I use SharedKeyLite authorization. However, when using SharedKey authorization, the authentication keeps on failing.
My guess is it's got to do something with the "Content-MD5" value in the Authorization signature. The documentation is a little vague on Content-MD5 value and I can't find a recommended way to generate Content-MD5 in the documentation.
I can't find an example using C#. The only example I found was using Powershell and that is using an empty string for Content-MD5. However, that doesn't work for my case.
Here is my code:
public static void CreateTable(string storageAccount, string storageKey, string tableName)
{
var client = new HttpClient();
string date = DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
client.DefaultRequestHeaders.Add("x-ms-date", date);
string msVersion = "2018-03-28";
client.DefaultRequestHeaders.Add("x-ms-version", msVersion);
client.DefaultRequestHeaders.Add("MaxDataServiceVersion", "3.0;NetFx");
client.DefaultRequestHeaders.Add("DataServiceVersion", "3.0;NetFx");
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=nometadata");
string payload = "{ \"TableName\":\""+ tableName +"\" }";
int contentLength = GetContentLength(payload);
string authH = "SharedKey " + storageAccount + ":" + CreateTableSignature("POST", payload, "application/json", date, storageAccount + "/Tables", storageKey, new List<string>() { });
client.DefaultRequestHeaders.Add("Authorization", authH);
string requestUri = $"https://{storageAccount}.table.core.windows.net/Tables";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
request.Content = new StringContent(payload,
Encoding.UTF8,
"application/json");
request.Content.Headers.ContentLength = contentLength;
client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
}
public static string CreateTableSignature(string verb, string content, string contentType, string date, string resource, string key, List<string> canonicalizedResourceParms)
{
string msgSignature = verb + "\n" +
CreateMD5(content) + "\n" +
contentType + "\n" +
date + "\n";
msgSignature += "/" + resource;
foreach (string parm in canonicalizedResourceParms)
msgSignature += "\n" + parm;
byte[] SignatureBytes = Encoding.UTF8.GetBytes(msgSignature);
// Create the HMACSHA256 version of the storage key.
HMACSHA256 SHA256 = new HMACSHA256(Convert.FromBase64String(key));
// Compute the hash of the SignatureBytes and convert it to a base64 string.
return Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));
}
public static string CreateMD5(string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
return Convert.ToBase64String(hashBytes);
}
}
Two points to fix.
Content-Type
request.Content = new StringContent(payload,
Encoding.UTF8,
"application/json");
In this method, SDK actually sets application/json; charset=utf-8 when we sending the request. This means the signature needs application/json; charset=utf-8 as well.
Or I recommend you to remove that misleading content type setting and use
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Content-MD5
It's not required in signature, you can leave it empty. Otherwise If you want to put it in the signature, you need to add corresponding request header first.
request.Content.Headers.ContentMD5 = Convert.FromBase64String(CreateMD5(payload));
Besides, in method CreateMD5(), Encoding should be UTF8
System.Text.Encoding.UTF8.GetBytes(input);

translate perl hash to C#

I have a perl script that hashes and hexes parameters for authenticating a post message. I have to write the same procedure in C#, but have had no luck so far. Here is the perl code:
my $sha1_user_pwd = sha1_base64($user_pwd);
$sha1_user_pwd .= '=' x (4 - (length($sha1_user_pwd) % 4));
my $sha1_ws_pwd = sha1_base64($ws_pwd);
$sha1_ws_pwd .= '=' x (4 - (length($sha1_ws_pwd) % 4)); # Padding; if neccesary.
my $utc_time = time;
my ($utc_time, $kontekst, $projekt, $userid, $sha1_user_pwd) = #_;
my $auth = calc_hmac($sha1_ws_pwd, $sha1_user_pwd, $utc_time, $kontekst, $projekt, $userid);
sub calc_hmac {
my ($sha1_ws_pwd, $sha1_user_pwd, $utc_time, $kontekst, $projekt, $userid) = #_;
my $hmac = Digest::HMAC_SHA1->new($sha1_ws_pwd . $sha1_user_pwd);
$hmac->add($utc_time . $kontekst . $projekt . $userid);
return $hmac->hex digest;
}
$kontekst, $projekt, $userid and $ws_userid are all original string values.
Final post message (i have inserted line breaks for readability)
wsBrugerid=$ws_userid
&UTCtime=$utc_time
&kontekst=$kontekst
&projekt=$projekt
&BrugerId=$userid
&Auth=$auth
I have tried to copy the procedure in C#:
const string APP_KEY = "APP_KEY";
Encoding enc = Encoding.ASCII;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(APP_KEY));
hmac.Initialize();
string ws_user = "ws_usr";
string ws_password = "ws_pwd";
DateTime epochStart = new System.DateTime(1970, 1, 1, 8, 0, 0, System.DateTimeKind.Utc);
int time = (int) (System.DateTime.UtcNow - epochStart).TotalSeconds;
string context = "context";
string project = "project";
string user_id = "user_id";
string user_pwd = "user_pwd";
string sha1_ws_pwd = System.Convert.ToBase64String(hmac.ComputeHash(enc.GetBytes(ws_password)));
sha1_ws_pwd += '=';
string sha1_user_pwd = System.Convert.ToBase64String(hmac.ComputeHash(enc.GetBytes(user_pwd)));
sha1_user_pwd += '=';
string k0 = sha1_ws_pwd + sha1_user_pwd;
string m0 = time + context + project + user_id;
byte[] _auth = hmac.ComputeHash(enc.GetBytes(k0 + m0));
string auth = BitConverter.ToString(_auth).Replace("-", string.Empty);
string url = "https://auth.emu.dk/mauth?wsBrugerid="+ws_user+
"&UTCtime="+time+
"&kontekst="+context+
"&projekt="+project+
"&BrugerId="+user_id+
"&Auth="+auth;
print("AuthenticationManager, url: " + url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
String responseString = "";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
using (Stream stream = response.GetResponseStream()){
StreamReader reader = new StreamReader(stream, encoding);
responseString = reader.ReadToEnd();
}
JSONNode json = JSON.Parse(responseString);
print("AuthenticationManager, response: " + json[0] + " - " + json[1]);
I have no access to the server or application, which gives the response. The real values has of course been swapped. For example, APP_KEY is not "APP_KEY", but instead an actual string used for authentication. I know the data is correct as it passes in the perl script.
I appreciate any help I can get very much.
I figured it out!
It was not the time, but instead it was the hmac key. I was using APP_KEY as key, but the perl script is using sha1_ws_pwd + sha1_user_pwd. (so that was a stupid mistake...)
my $hmac = Digest::HMAC_SHA1->new($sha1_ws_pwd . $sha1_user_pwd);
Finally i also had to lower case the auth in C#. So the change in C# was:
// sha1 hash the passwords
string sha1_ws_pwd = System.Convert.ToBase64String(sha1.ComputeHash(enc.GetBytes(ws_password)));
string sha1_user_pwd = System.Convert.ToBase64String(sha1.ComputeHash(enc.GetBytes(user_pwd)));
…
string k0 = sha1_ws_pwd + sha1_user_pwd;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(k0));
…
string auth = BitConverter.ToString(_auth).Replace("-", string.Empty).ToLower();
Thank you for your time and answers.

HMAC validation Failure with code 403

I have been exploring payeezy api from last three days. I am just making a simple http web request from a C# application. I have followed all the steps mentions and correctly verified each and everything. Below is the detail per item.
API Key :- I have verified my api key its correct.
API Secret :- It is also correct.
merchant token :- It is also verified.
Nonce :- I have created cryptographically strong random number as following.
RandomNumberGenerator rng = new RNGCryptoServiceProvider();
byte[] nonceData = new byte[18];
rng.GetBytes(nonceData);
string nonce = BitConverter.ToUInt64(nonceData,0).ToString();
Timestamp :-
string timestamp = Convert.ToInt64(ts.TotalMilliseconds).ToString();
Payload :-
{"merchant_ref":"Astonishing-Sale","transaction_type":"authorize","method":"credit_card","amount":"1299","currency_code":"USD","credit_card":{"type":"visa","cardholder_name":"John Smith","card_number":"4788250000028291","exp_date":"1020","cvv":"123"}}
Then I have created HMAC as following.
private string CreateAuthorization(string data, string secret)
{
// data is in following format.
// data = apiKey + nonce + timestamp + token + payload;
secret = secret ?? "";
using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
{
byte[] hashdata = hmacsha256.ComputeHash(Encoding.UTF32.GetBytes(data));
return Convert.ToBase64String(hashdata);
}
}
Now I am getting hmac validation error. My generated hmac string is 64 bit while on your website under docs and sandbox its 86 bit.
Can you please assist me in this as I am stuck on this issue from last three days.
Thanks
These are the common causes for “HMAC validation Failure”:
API key and/or API secret are incorrect.
Leading or trailing spaces in the API key, API secret, merchant token.
Timestamp in the HTTP header is not in milliseconds.
Timestamp in the HTTP header does not represent EPOCH time.
Timestamp in the HTTP header is not within 5 minutes of our server time.
System time is not accurate.
Here is a sample c# code to generate HMAC:
public byte[] CalculateHMAC(string data, string secret)
{
HMAC hmacSha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
byte[] hmac2Hex = hmacSha256.ComputeHash(Encoding.UTF8.GetBytes(data));
string hex = BitConverter.ToString(hmac2Hex);
hex = hex.Replace("-","").ToLower();
byte[] hexArray = Encoding.UTF8.GetBytes(hex);
return hexArray;
}
protected void Button1_Click(object sender, EventArgs e)
{
string jsonString = "{ \"merchant_ref\": \"MVC Test\", \"transaction_type\": \"authorize\", \"method\": \"credit_card\", \"amount\": \"1299\", \"currency_code\": \"USD\", \"credit_card\": { \"type\": \"visa\", \"cardholder_name\": \"Test Name\", \"card_number\": \"4005519200000004\", \"exp_date\": \"1020\", \"cvv\": \"123\" } }";
Random random = new Random();
string nonce = (random.Next(0, 1000000)).ToString();
DateTime date = DateTime.UtcNow;
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan span = (date - epoch);
string time = span.TotalSeconds.ToString();
string token = Request.Form["token"];//Merchant token
string apiKey = Request.Form["apikey"];//apikey
string apiSecret = Request.Form["apisecret"];//API secret
string hashData = apiKey+nonce+time+token+jsonString;
string base64Hash = Convert.ToBase64String(CalculateHMAC(hashData, apiSecret));
string url = "https://api-cert.payeezy.com/v1/transactions";
//begin HttpWebRequest
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.Accept = "*/*";
webRequest.Headers.Add("timestamp", time);
webRequest.Headers.Add("nonce", nonce);
webRequest.Headers.Add("token", token);
webRequest.Headers.Add("apikey", apiKey);
webRequest.Headers.Add("Authorization", base64Hash );
webRequest.ContentLength = jsonString.Length;
webRequest.ContentType = "application/json";
StreamWriter writer = null;
writer = new StreamWriter(webRequest.GetRequestStream());
writer.Write(jsonString);
writer.Close();
string responseString;
try
{
using(HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader responseStream = new StreamReader(webResponse.GetResponseStream()))
{
responseString = responseStream.ReadToEnd();
request_label.Text = "<h3>Request</h3><br />" + webRequest.Headers.ToString() + System.Web.HttpUtility.HtmlEncode(jsonString);
response_label.Text = "<h3>Response</h3><br />" + webResponse.Headers.ToString() + System.Web.HttpUtility.HtmlEncode(responseString);
}
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response)
{
using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream()))
{
string remoteEx = reader.ReadToEnd();
error.Text = remoteEx;
}
}
}
}
}
I've been working on an integration and it's working great; maybe you can take a peek
https://github.com/clifton-io/Clifton.Payment
Specifically you'll want to look here:
https://github.com/clifton-io/Clifton.Payment/blob/cc4053b0bfe05f2453dc508e96a649fc138b973c/Clifton.Payment/Gateway/Payeezy/PayeezyGateway.cs#L66
Best of luck :)

API exception while calling 'DataWarehouseGetReportData' in C#

I am using Omniture api to download a report. The report is completed when I checked the status with DataWarehouseCheckRequest method. Now when I try to fetch the report using DataWarehouseGetReportData method, I get
CommunicationException Error in deserializing body of reply message for operation 'DataWarehouseGetReportData
Inner exception says
The specified type was not recognized: name='data_warehouse_report_row', namespace='http://www.omniture.com/', at <rows xmlns=''>
I am new with C# and the API both. Got no idea how to resolve this. Please help.
Thanks
When you want to download a DW report the best option is to do it over http. This the standard way and is much more efficient.
The response to CheckRequest contains a DataURL. Use that to download the data.
Here is some c# sample code I am using for an almost identical API (Partner vs you Enterprise API) (note I'm no c# expert either, so you will need to do a code review on this).
HttpWebResponse statusResponse = null;
string response = "";
StringBuilder sbUrl = new StringBuilder(dwrq.data_url); // hardcode to variable "rest_url" for testing.
HttpWebRequest omniRequest = (HttpWebRequest)WebRequest.Create(sbUrl.ToString());
string timecreated = generateTimestamp();
string nonce = generateNonce();
string digest = getBase64Digest(nonce + timecreated + secret);
nonce = base64Encode(nonce);
omniRequest.Headers.Add("X-WSSE: UsernameToken Username=\"" + username + "\", PasswordDigest=\"" + digest + "\", Nonce=\"" + nonce + "\", Created=\"" + timecreated + "\"");
omniRequest.Method = "GET"; // Switched from POST as GET is the right HTTP verb in this case
try
{
statusResponse = (HttpWebResponse)omniRequest.GetResponse();
using (Stream receiveStream = statusResponse.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
response = readStream.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
Console.WriteLine("Response is a TAB delimeted CSV structure. Printing to screen.");
Console.WriteLine(response);
Console.WriteLine("Ending REST...");
Console.WriteLine("Ending ExportRequestSegmentedData...");
and the supporting methods
/*** Here are the private functions ***/
// Encrypting passwords with SHA1 in .NET and Java
// http://authors.aspalliance.com/thycotic/articles/view.aspx?id=2
private static string getBase64Digest(string input)
{
SHA1 sha = new SHA1Managed();
ASCIIEncoding ae = new ASCIIEncoding();
byte[] data = ae.GetBytes(input);
byte[] digest = sha.ComputeHash(data);
return Convert.ToBase64String(digest);
}
// generate random nonce
private static string generateNonce()
{
Random random = new Random();
int len = 24;
string chars = "0123456789abcdef";
string nonce = "";
for (int i = 0; i < len; i++)
{
nonce += chars.Substring(Convert.ToInt32(Math.Floor(random.NextDouble() * chars.Length)), 1);
}
return nonce;
}
// Time stamp in UTC string
private static string generateTimestamp()
{
return DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
// C#-Base64 Encoding
// http://www.vbforums.com/showthread.php?t=287324
public static string base64Encode(string data)
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
Best of Luck! C.

Categories

Resources