I get error invalid oauth_signature:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Web;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var time_stamp = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
string consumer_key = "MyConsumerKey";
string signature_method = "HMAC-SHA1";
string nonce = RandomString(32);
string signature;
string key = "MyConsumerSecret&";
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
//hm.Key = key;
//HMACSHA1.Create().Initialize();
byte[] keyByte = encoding.GetBytes(key);
string baseUrl = String.Format("method=vimeo.people.search&oauth_consumer_key={0}&oauth_signature_method=HMAC-SHA1&oauth_timestamp={1}&oauth_version=1.0", consumer_key, time_stamp);
byte[] baseMessage = encoding.GetBytes(baseUrl);
HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
byte[] hashmessage = hmacsha1.ComputeHash(baseMessage);
byte[] encode = System.Text.ASCIIEncoding.ASCII.GetBytes(hashmessage.ToString());
signature = System.Convert.ToBase64String(encode);
Console.WriteLine("signature: " + signature);
string url = String.Format("http://vimeo.com/api/rest/v2?method=vimeo.videos.search&query=ssaa&api_key=API_KEY&oauth_consumer_key={0}&oauth_version=1.0&oauth_signature_method={1}&oauth_timestamp={2}&oauth_nonce={3}&oauth_token=478fa9c8bc5834e60a4fae7688aa0c8e&oauth_signature={4}", consumer_key, signature_method, time_stamp, nonce,signature);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader stream = new StreamReader(resp.GetResponseStream());
string html = stream.ReadToEnd();
Console.WriteLine(html);
}
private static string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
}
}
Related
I'm trying to set up a messing server for me and my friends and I ran into issues with RSA Decryption.
The correct keys are used
If I enable OAEP padding I get a error that simply states "OAEPpadding"
I'm losing my mind on this bug, I'm posting the script below.
Encryption works fine, its just decryption that's problematic
Please Help
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Xml.Serialization;
namespace Server_WIN_
{
class Program
{
public static XmlSerializer xs = new XmlSerializer(typeof(RSAParameters));
public static TcpListener server = new TcpListener(IPAddress.Parse("192.168.1.93"), 78);
public static TcpClient client = null;
public static NetworkStream canwetalk = null;
public static RSACryptoServiceProvider csp = new RSACryptoServiceProvider(4096);
public static RSAParameters publickey;
public static RSAParameters privatekey;
static Program()
{
server.Start();
csp.PersistKeyInCsp = false;
publickey = csp.ExportParameters(false);
privatekey = csp.ExportParameters(true);
client = server.AcceptTcpClient();
canwetalk = client.GetStream();
}
public static void Main(string[] args)
{
string strHostName = "";
strHostName = Dns.GetHostName();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
Random ran = new Random();
HashAlgorithm sha = SHA256.Create();
string msg = "";
byte[] buffer = new byte[4096];
msg = "test";
msg = Encrypt(msg);
msg = Decrypt(msg);
Console.WriteLine(msg);
}
public static string PublicKeyString()
{
byte[] bytes = new byte[4096];
var sw = new StringWriter();
var xs = new XmlSerializer(typeof(RSAParameters));
xs.Serialize(sw, publickey);
return sw.ToString();
}
public static string PrivateKeyString()
{
byte[] bytes = new byte[4096];
var sw = new StringWriter();
var xs = new XmlSerializer(typeof(RSAParameters));
xs.Serialize(sw, privatekey);
return sw.ToString();
}
public static string Encrypt(string msg)
{
csp.ImportParameters(publickey);
byte[] data = System.Text.Encoding.ASCII.GetBytes(msg);
byte[] cipher = csp.Encrypt(data, false);
return System.Text.Encoding.ASCII.GetString(cipher);
}
public static string Decrypt(string msg)
{
try
{
csp.ImportParameters(privatekey);
byte[] decrypted = csp.Decrypt(System.Text.Encoding.ASCII.GetBytes(msg), false);
return System.Text.Encoding.Unicode.GetString(decrypted);
}
catch(CryptographicException e)
{
string p = e.ToString();
Console.WriteLine(p);
}
return "";
}
public static void ExportPublicKey()
{
string msg = PublicKeyString();
byte[] buffer = new byte[4096];
byte[] msg1 = System.Text.Encoding.ASCII.GetBytes(msg);
canwetalk.Write(msg1, 0, msg1.Length);
}
public static void ToStream(string msg, bool Encryption)
{
if (Encryption)
{
msg = Encrypt(msg);
byte[] msgbytes = System.Text.Encoding.ASCII.GetBytes(msg);
canwetalk.Write(msgbytes, 0, msgbytes.Length);
}
else
{
byte[] msgbytes = System.Text.Encoding.ASCII.GetBytes(msg);
canwetalk.Write(msgbytes, 0, msgbytes.Length);
}
}
public static string ReadStream()
{
byte[] buffer = new byte[4096];
int i = canwetalk.Read(buffer,0,buffer.Length);
return System.Text.Encoding.ASCII.GetString(buffer,0,i);
}
}
You can find this stackoverflow question helpful, but it's quite out of date Error occurred while decoding OAEP padding
Don't use the same provider. Do this instead:
var publicKey = RSA.Create();
publicKey.ImportParameters(PUB_PARAMS);
var privateKey = RSA.Create();
privateKey.ImportParameters(PRIV_PARAMS);
I have this class 'IdentityConfig.cs and Helper.cs', On IdentityConfig i am calling Helper class to access Decrypt method with its argument list. Somehow i dont seem to get this and i am getting an error called Decrypt does not exist or am i missing some directive. How do i fix this issue and calling the correct package. Please help me mates to resolve this issue.
// IdentityConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using System.Net.Mail;
using eNtsaTrainingRegistration.Models;
using System.Web.Configuration;
using System.Net;
namespace eNtsaTrainingRegistration.App_Start
{
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
var mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress(message.Destination));
mailMessage.From = new MailAddress("Gcobani Mkontwana <ggcobani#gmail.com>");
mailMessage.Subject = message.Subject;
mailMessage.IsBodyHtml = true;
mailMessage.Body = message.Body;
using(var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = WebConfigurationManager.AppSettings["UserName"],
Password = Helper.Decrypt(WebConfigurationManager.AppSettings["UserPasswd"])
};
smtp.Credentials = credential;
smtp.Host = WebConfigurationManager.AppSettings["SMTPName"];
smtp.Port = int.Parse(WebConfigurationManager.AppSettings["SMTPPort"]);
smtp.EnableSsl = true;
smtp.Send(mailMessage);
}
return Task.FromResult(0);
}
}
}
// Helper class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace eNtsaTrainingRegistration.Helper
{
public class Helper
{
private const string PassPhrase = "3pAc0j$_56K?_S7c9gS!";
//Encrypt password.
public static string Encrypt(string strValue)
{
byte[] results;
UTF8Encoding uTF8 = new UTF8Encoding();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] deskey = md5.ComputeHash(uTF8.GetBytes(PassPhrase));
TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
desalg.Key = deskey;
desalg.Mode = CipherMode.ECB;
desalg.Padding = PaddingMode.PKCS7;
byte[] encrypt_data = uTF8.GetBytes(strValue);
try
{
ICryptoTransform encrytor = desalg.CreateEncryptor();
results = encrytor.TransformFinalBlock(encrypt_data, 0, encrypt_data.Length);
}
finally
{
desalg.Clear();
md5.Clear();
}
return Convert.ToBase64String(results);
}
//Decrypt password.
public static string Decrypt(string strValue)
{
byte[] results;
UTF8Encoding uTF8 = new UTF8Encoding();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] deskey = md5.ComputeHash(uTF8.GetBytes(PassPhrase));
TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
desalg.Key = deskey;
desalg.Mode = CipherMode.ECB;
desalg.Padding = PaddingMode.PKCS7;
byte[] decrypt_data = Convert.FromBase64String(strValue);
try
{
ICryptoTransform decryptor = desalg.CreateDecryptor();
results = decryptor.TransformFinalBlock(decrypt_data, 0, decrypt_data.Length);
}
finally
{
desalg.Clear();
md5.Clear();
}
return uTF8.GetString(results);
}
// In between space
public static string GetBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if(strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}else
{
return "";
}
}
public static string BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
if (byteCount == 0)
return string.Format("{0} {1}", 0, suf[0]);
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return string.Format("{0} {1}", (Math.Sign(byteCount) * num).ToString(), suf[place]);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace eNtsaTrainingRegistration
{
public class Helper_b
{
private const string PassPhrase = "3pAc0j$_56K?_S7c9gS!";
//Encrypt password.
public static string Encrypt(string strValue)
{
byte[] results;
UTF8Encoding uTF8 = new UTF8Encoding();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] deskey = md5.ComputeHash(uTF8.GetBytes(PassPhrase));
TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
desalg.Key = deskey;
desalg.Mode = CipherMode.ECB;
desalg.Padding = PaddingMode.PKCS7;
byte[] encrypt_data = uTF8.GetBytes(strValue);
try
{
ICryptoTransform encrytor = desalg.CreateEncryptor();
results = encrytor.TransformFinalBlock(encrypt_data, 0, encrypt_data.Length);
}
finally
{
desalg.Clear();
md5.Clear();
}
return Convert.ToBase64String(results);
}
//Decrypt password.
public static string Decrypt(string strValue)
{
byte[] results;
UTF8Encoding uTF8 = new UTF8Encoding();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] deskey = md5.ComputeHash(uTF8.GetBytes(PassPhrase));
TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
desalg.Key = deskey;
desalg.Mode = CipherMode.ECB;
desalg.Padding = PaddingMode.PKCS7;
byte[] decrypt_data = Convert.FromBase64String(strValue);
try
{
ICryptoTransform decryptor = desalg.CreateDecryptor();
results = decryptor.TransformFinalBlock(decrypt_data, 0, decrypt_data.Length);
}
finally
{
desalg.Clear();
md5.Clear();
}
return uTF8.GetString(results);
}
// In between space
public static string GetBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if(strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}else
{
return "";
}
}
public static string BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
if (byteCount == 0)
return string.Format("{0} {1}", 0, suf[0]);
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return string.Format("{0} {1}", (Math.Sign(byteCount) * num).ToString(), suf[place]);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using eNtsaTrainingRegistration.Models;
using System.Net.Mail;
using System.Net;
using System.Web.Configuration;
namespace eNtsaTrainingRegistration
{
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
var mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress(message.Destination));
mailMessage.From = new MailAddress("Gcobani Mkontwana <ggcobani#gmail.com>");
mailMessage.Subject = message.Subject;
mailMessage.IsBodyHtml = true;
mailMessage.Body = message.Body;
using(var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = WebConfigurationManager.AppSettings["UserName"],
Password = Helper_b.Decrypt(WebConfigurationManager.AppSettings["UserPassword"])
};
smtp.Credentials = credential;
smtp.Host = WebConfigurationManager.AppSettings["SMTPName"];
smtp.Port = int.Parse(WebConfigurationManager.AppSettings["SMTPPort"]);
smtp.EnableSsl = true;
smtp.Send(mailMessage);
}
return Task.FromResult(0);
}
}
}
I have been mainly writing in PHP and only know one way to create an aes encryption for a variable:
aes_encrypt(variableName, 'SecretSalt')
I need to encrypt a variable in C# and I have tried a similar approach as in PHP but it is not working (I get an error "The name aes does not exist in current context"
Here is my current code in C#:
var username = txtusername.Text;
var password = txtpassword.Text;
var usernameAES = aes_encrypt(username, 'mySalt');
What is the correct way to use AES_ENCRYPT? I am sending the variable to a PHP Web Service
Update:
More C# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Threading;
private void Login()
{
if (String.IsNullOrEmpty(txtusername.Text))
{
MessageBox.Show("Please insert username");
}
if (String.IsNullOrEmpty(txtpassword.Text))
{
MessageBox.Show("Please insert password");
}
var Token = "TMMZC 77385 R8G2D6";
var username = txtusername.Text;
var password = txtpassword.Text;
var usernameAES = aes_encrypt(username, 'mySalt');
var url = "https://mydomain.co.za/LoginVerification.php?";
var var = "username=" + username + "&password=" + password + "&Token=" + Token Token;
var URL = url + var;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
var responseFromServer = reader.ReadToEnd();
//MessageBox.Show(responseFromServer);
// Display the content.
if (responseFromServer == "Allow")
{
//Open Form1
Form1 Form = new Form1();
Form.Show();
//CLose Password Form
Password PasswordForm = new Password();
PasswordForm.Close();
}
try this code
using System.Security.Cryptography;
using System.IO;
public string EncryptText(string input, string password)
{
// Get the bytes of the string
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
// Hash the password with SHA256
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
public byte[] aes_encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
I have a game made with Unity which is deployed in the WP store and I am trying to do the same for BB... however, after checking everything I have realized that I canĀ“t post the score I have made, into the DB I host online...
I think it is because of the MD5 function but I am not sure which are the APIs, BB uses...
Can anyone help me out a little, here, please?
This is the MD5 function I have (written in C#)
using UnityEngine;
using System.Collections;
using System.Text;
using System;
#if UNITY_WP8
using System.Security.Cryptography;
using UnityEngine.Windows;
using UnityEngine.WindowsPhone;
#else
using System.Security.Cryptography;
#endif
public static class Md5Functions
{
#if UNITY_WP8
static string md5val;
// Use this for initialization
static void Start () {
md5val = Md5Sum("Hello World!");
}
static void OnGUI()
{
GUILayout.Label(md5val);
}
public static string Md5Sum(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
byte[] hashBytes = Crypto.ComputeMD5Hash(bytes);
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
#else
public static string Md5Sum(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
// encrypt bytes
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
#endif
}
Thanks!
I am trying to make use of a REST API using C#. The API creator has provided sample libraries in PHP, Ruby and Java. I am getting hung up on one part of it where I need to generate an HMAC.
Here's how it is done in the sample libraries they have provided.
PHP
hash_hmac('sha1', $signatureString, $secretKey, false);
Ruby
digest = OpenSSL::Digest::Digest.new('sha1')
return OpenSSL::HMAC.hexdigest(digest, secretKey, signatureString)
Java
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = null;
mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] bytes = mac.doFinal(signatureString.getBytes());
String form = "";
for (int i = 0; i < bytes.length; i++)
{
String str = Integer.toHexString(((int)bytes[i]) & 0xff);
if (str.length() == 1)
{
str = "0" + str;
}
form = form + str;
}
return form;
Here's my attempt in C#. It is not working. UPDATE: The C# example below works just fine. I found out that the real problem was due to some cross-platform differences in newline characters in my signatureString.
var enc = Encoding.ASCII;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize();
byte[] buffer = enc.GetBytes(signatureString);
return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();
an extension to Vimvq1987's answer:
return hashValue.ToString(); doesn't produce the output you want/need. You have to convert the bytes in the array hashValue to their hex-string representation.
Can be as simple as return BitConverter.toString(hashValue); (prints upper-case letters A-F) or if you like it a bit more complex:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
public static string Encode(string input, byte[] key)
{
HMACSHA1 myhmacsha1 = new HMACSHA1(key);
byte[] byteArray = Encoding.ASCII.GetBytes(input);
MemoryStream stream = new MemoryStream(byteArray);
return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}",e), s => s );
}
static void Main(string[] args)
{
byte[] key = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz");
string input = "";
foreach (string s in new string[] { "Marry", " had", " a", " little", " lamb" })
{
input += s;
System.Console.WriteLine( Encode(input, key) );
}
return;
}
}
}
which prints
3545e064fb59bc4bfc02b6e1c3d4925c898aa504
3249f4c8468d4d67f465937da05b809eaff22fdb
87baaadf5d096677f944015e53d283834eb1e943
6325376820c29a09e3ab30db000033aa71d6927d
54579b0146e2476595381d837ee38863be358213
and I get the exact same result for
<?php
$secretKey = 'abcdefghijklmnopqrstuvwxyz';
$signatureString = '';
foreach( array('Marry',' had',' a',' little',' lamb') as $s ) {
$signatureString .= $s;
echo hash_hmac('sha1', $signatureString, $secretKey, false), "\n";
}
edit: Dmitriy Nemykin suggested the following edit
public static string Encode(string input, byte[] key)
{
byte[] byteArray = Encoding.ASCII.GetBytes(input);
using(var myhmacsha1 = new HMACSHA1(key))
{
var hashArray = myhmacsha1.ComputeHash(byteArray);
return hashArray.Aggregate("", (s, e) => s + String.Format("{0:x2}",e), s => s );
}
}
which was rejected. But as James already pointed out in a comment to this answer at the very least the using statement is a good point.
This site has some pretty good examples across languages: http://jokecamp.wordpress.com/2012/10/21/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/
The c# implementation at the time of writing is:
private string CreateToken(string message, string secret)
{
secret = secret ?? "";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
Try this:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha1.aspx
quick and dirty code:
public string Encode(string input, byte [] key)
{
HMACSHA1 myhmacsha1 = new HMACSHA1(key);
byte[] byteArray = Encoding.ASCII.GetBytes( input );
MemoryStream stream = new MemoryStream( byteArray );
byte[] hashValue = myhmacsha1.ComputeHash(stream);
return hashValue.ToString();
}