Skip to content

Instantly share code, notes, and snippets.

@leegould
Created February 17, 2012 12:46
Show Gist options
  • Save leegould/1853228 to your computer and use it in GitHub Desktop.
Save leegould/1853228 to your computer and use it in GitHub Desktop.
Soap Password Digest
using System;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
namespace SoapServices
{
///
/// Example class for creating a Password Digest Header in .Net
///
public class PasswordDigestRequest
{
internal string Username { get; set; }
internal string Password { get; set; }
internal string Created { get; set; }
///
/// Initializes a new instance of the PasswordDigestRequest class.
///
public PasswordDigestRequest()
{
Username = ConfigurationManager.AppSettings["WebServiceUsername"];
Password = ConfigurationManager.AppSettings["WebServicePassword"];
Created = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
}
///
/// Creates the header.
///
internal string CreateHeader()
{
byte[] nonce = GetNonce();
string nonceStr = Convert.ToBase64String(nonce);
string hashedPassword = CreateHashedPassword(nonce, Created, Password);
var soapStr = new StringBuilder();
soapStr.Append("");
soapStr.Append("");
soapStr.Append("");
soapStr.Append("");
soapStr.Append(Username);
soapStr.Append("");
soapStr.Append("");
soapStr.Append(hashedPassword);
soapStr.Append("");
soapStr.Append("");
soapStr.Append(nonceStr);
soapStr.Append("");
soapStr.Append("");
soapStr.Append(Created);
soapStr.Append("");
soapStr.Append("");
soapStr.Append("");
soapStr.Append("");
return soapStr.ToString();
}
///
/// Creates the hashed password.
///
internal static string CreateHashedPassword(byte[] nonce, string created, string password)
{
byte[] createdBytes = Encoding.UTF8.GetBytes(created);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] combined = new byte[createdBytes.Length + nonce.Length + passwordBytes.Length];
Buffer.BlockCopy(nonce, 0, combined, 0, nonce.Length);
Buffer.BlockCopy(createdBytes, 0, combined, nonce.Length, createdBytes.Length);
Buffer.BlockCopy(passwordBytes, 0, combined, nonce.Length + createdBytes.Length, passwordBytes.Length);
return Convert.ToBase64String(SHA1.Create().ComputeHash(combined));
}
///
/// Create a Nonce
/// returns a random nonce.
internal static byte[] GetNonce()
{
byte[] nonce = new byte[0x10];
RandomNumberGenerator generator = new RNGCryptoServiceProvider();
generator.GetBytes(nonce);
return nonce;
}
}
}
@ftitzwalter
Copy link

fritz1234

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment