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.
Related
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
}
}
I have some code here and I am getting and error 401 unauthorized. I have checked the sign in with twitter box.
public async Task get_Oauth_token_TaskAsync()
{
//variables for action
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;
oauth_timestamp = seconds.ToString();
oauth_callback = "http://www.localhost:55593/TwitterSync.aspx";
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();
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 = "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 ByteToString(hmac.ComputeHash(Encoding.UTF32.GetBytes(value)));
}
}
static string ByteToString(IEnumerable<byte> data)
{
return string.Concat(data.Select(b => b.ToString("x2")));
}
I did everything according to this page . Now I am just lost, any Idea why does it not work?
You are not calculating the oauth_timestamp correctly. This should be calculated as Unix time which is the number of seconds since 00:00:00 UTC on 1 Jan 1970.
int unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
or using .NET 4.6
long unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
Also the signing key used for creating the signature should be a concatenation of the percent encoded consumer secret and the percent encoded token secret joined by an ampersand (&). In the case of obtaining a request token the token secret is not yet known so you should just use the consumer secret followed by an ampersand (&).
var signingKey = oauth_consumer_key_enc + "&";
Finally you should return the Base64 encoded string after you have computed your hash so your function becomes:
private string ShaHash(string value, string signingKey)
{
using (var hmac = new HMACSHA1(Encoding.ASCII.GetBytes(signingKey)))
{
return Convert.ToBase64String(hmac.ComputeHash(Encoding.ASCII.GetBytes(value)));
}
}
The following code I have written in C#. Can anyone please help me?
public string Verify_Credentials(string oauthconsumerkey, string oauthconsumersecret, string oauthtoken, string oauthtokensecret)
{
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("oauth_version", "1.0");
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", "HMAC-SHA1");
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
basestringParameters.Add("oauth_token", oauthtoken);
//GS - Build the signature string
StringBuilder baseString = new StringBuilder();
baseString.Append("GET" + "&");
baseString.Append(EncodeCharacters(Uri.EscapeDataString("https://api.twitter.com/1.1/account/verify_credentials.json") + "&"));
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
}
//Since the baseString is urlEncoded we have to remove the last 3 chars - %26
string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);
//Build the signing key
string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));
//Sign the request
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));
string responseFromServer = string.Empty;
//Tell Twitter we don't do the 100 continue thing
ServicePointManager.Expect100Continue = false;
//authorization header
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(
#"https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true");
StringBuilder authorizationHeaderParams = new StringBuilder();
authorizationHeaderParams.Append("OAuth ");
authorizationHeaderParams.Append("include_email=" + "\"" + "true" + "\",");
authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
if (!string.IsNullOrEmpty(oauthtoken))
authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
hwr.Headers.Add("Authorization", authorizationHeaderParams.ToString());
hwr.Method = "GET";
hwr.ContentType = "application/x-www-form-urlencoded";
//Allow us a reasonable timeout in case Twitter's busy
hwr.Timeout = 3 * 60 * 1000;
try
{
// hwr.Proxy = new WebProxy("enter proxy details/address");
HttpWebResponse rsp = hwr.GetResponse() as HttpWebResponse;
Stream dataStream = rsp.GetResponseStream();
//Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
//Read the content.
responseFromServer = reader.ReadToEnd();
}
catch (Exception ex)
{
}
return responseFromServer;
}
private string EncodeCharacters(string data)
{
//as per OAuth Core 1.0 Characters in the unreserved character set MUST NOT be encoded
//unreserved = ALPHA, DIGIT, '-', '.', '_', '~'
if (data.Contains("!"))
data = data.Replace("!", "%21");
if (data.Contains("'"))
data = data.Replace("'", "%27");
if (data.Contains("("))
data = data.Replace("(", "%28");
if (data.Contains(")"))
data = data.Replace(")", "%29");
if (data.Contains("*"))
data = data.Replace("*", "%2A");
if (data.Contains(","))
data = data.Replace(",", "%2C");
return data;
}
Your App must be whitelisted by Twitter in order to get email from:
https://api.twitter.com/1.1/account/verify_credentials.json
So if you remove ?include_email=true part of the request url you will get a response with some fields and then you can get the screen_name of the user for example.
You can ask to be whitelisted using the form bellow (check > "I need access to special permissions"):
https://support.twitter.com/forms/platform
In my case they granted me access after some few hours...
More info: https://dev.twitter.com/rest/reference/get/account/verify_credentials
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 :)
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.