Skip to content

Instantly share code, notes, and snippets.

@TimHeckel
Created January 20, 2012 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TimHeckel/1644084 to your computer and use it in GitHub Desktop.
Save TimHeckel/1644084 to your computer and use it in GitHub Desktop.
Generating an SSO token for integration with Tenderapp.com using c# / .NET
//Third party dependencies: Newtonsoft JSON Library
public class TenderHelpService
{
public string SiteKey
{
get { return "your_site_key"; }
}
public string ApiKey
{
get { return "your_api_key"; }
}
public string BuildSSOToken(User user)
{
//user is simply an object that stores some information about your user
var userDetails = JsonConvert.SerializeObject(
new
{
name = user.UserName
,email = user.Email
,unique_id = user.Id
,trusted = true
,expires = DateTime.Now.ToUniversalTime().AddHours(15).ToString("ddd MMM dd hh:mm:ss UTC yyyy")
}
);
string initVector = "OpenSSL for Ruby";
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] keyBytesLong;
using (SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider())
{
keyBytesLong = sha.ComputeHash(Encoding.UTF8.GetBytes(ApiKey + SiteKey));
}
byte[] keyBytes = new byte[16];
Array.Copy(keyBytesLong, keyBytes, 16);
string ud = JsonConvert.SerializeObject(userDetails).Replace(@"\", "");
ud = ud.Substring(1, ud.Length - 2);
byte[] textBytes = Encoding.UTF8.GetBytes(ud);
for (int i = 0; i < 16; i++)
{
textBytes[i] ^= initVectorBytes[i];
}
// Encrypt the string to an array of bytes
byte[] encrypted = aes(textBytes, keyBytes, initVectorBytes);
string token = Convert.ToBase64String(encrypted);
token = token.Replace("+", "-").Replace("/", "_").Replace(Environment.NewLine, "");
token = (token.Substring(token.Length - 1, 1) == "=") ? token.Substring(0, token.Length - 2) : token;
return token;
}
static byte[] aes(byte[] textBytes, byte[] Key, byte[] IV)
{
// Declare the stream used to encrypt to an in memory
// array of bytes and the RijndaelManaged object
// used to encrypt the data.
using (MemoryStream msEncrypt = new MemoryStream())
using (RijndaelManaged aesAlg = new RijndaelManaged())
{
// Provide the RijndaelManaged object with the specified key and IV.
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.KeySize = 128;
aesAlg.BlockSize = 128;
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create an encrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor();
// Create the streams used for encryption.
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(textBytes, 0, textBytes.Length);
csEncrypt.FlushFinalBlock();
}
byte[] encrypted = msEncrypt.ToArray();
// Return the encrypted bytes from the memory stream.
return encrypted;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment