[.NET]SAMLRequest, SAMLResponse快速加解密(或叫編碼解碼)範例

  • 1041
  • 0

[.NET]SAMLRequest, SAMLResponse快速加解密(或叫編碼解碼)範例

一、沒有用Deflate演算法去壓縮字串的版本:

void Main()
{
	string abc = @"我是誰";
	string base64Content = EncodeSAML(abc);
	Console.WriteLine(base64Content);
	//base64Content.Dump();

	string decodeResult = DecodeSAML(base64Content);
	Console.WriteLine(decodeResult);
	//	decodeResult.Dump();


}

private static string EncodeSAML(string src)
{
	byte[] bytes = System.Text.Encoding.UTF8.GetBytes(src);
	string base64String = Convert.ToBase64String(bytes);
	base64String = HttpUtility.UrlEncode(base64String);
	return base64String;


}

// Define other methods and classes here
private static string DecodeSAML(string rawSamlData)
{
	string samlAssertion = "";
	// spec says "SAMLResponse=" 
	//string rawSamlData = Request["SAMLResponse"];

	// the sample data sent us may be already encoded, 
	// which results in double encoding
	if (rawSamlData.Contains('%'))
	{
		rawSamlData = HttpUtility.UrlDecode(rawSamlData);
	}

	// read the base64 encoded bytes
	byte[] samlData = Convert.FromBase64String(rawSamlData);

	// read back into a UTF string
	samlAssertion = System.Text.Encoding.UTF8.GetString(samlData);

	return samlAssertion;
}


執行結果:


二、有用Deflate演算法去壓縮字串的版本:(業界比較多採用這種)

void Main()
{
	string abc = @"我是誰";
	string base64Content = EncodeSamlAuthnRequest(abc);
	Console.WriteLine(base64Content);
	//base64Content.Dump();

	string decodeResult = DecodeSamlAuthnRequest(base64Content);
	Console.WriteLine(decodeResult);
	//	decodeResult.Dump();
}

// Define other methods and classes here

public static string EncodeSamlAuthnRequest(string authnRequest) {
    var bytes = Encoding.UTF8.GetBytes(authnRequest);
    using (var output = new MemoryStream()) {
      using (var zip = new DeflateStream(output, CompressionMode.Compress)) {
        zip.Write(bytes, 0, bytes.Length);
      }
      var base64 = Convert.ToBase64String(output.ToArray());
      return HttpUtility.UrlEncode(base64);
	}
}

public static string DecodeSamlAuthnRequest(string encodedAuthnRequest)
{
	var utf8 = Encoding.UTF8;
	var bytes = Convert.FromBase64String(HttpUtility.UrlDecode(encodedAuthnRequest));
	using (var output = new MemoryStream())
	{
		using (var input = new MemoryStream(bytes))
		{
			using (var unzip = new DeflateStream(input, CompressionMode.Decompress))
			{
				unzip.CopyTo(output, bytes.Length);
				unzip.Close();
			}
			return utf8.GetString(output.ToArray());
		}
	}
}


執行結果:


參考資料:
How do I correctly prepare an 'HTTP Redirect Binding' SAML Request using C#
https://stackoverflow.com/questions/12090403/how-do-i-correctly-prepare-an-http-redirect-binding-saml-request-using-c-sharp
zip and unzip string with Deflate
​https://stackoverflow.com/questions/2118904/zip-and-unzip-string-with-deflate
How to parse a SAML assertion request in .Net
https://stackoverflow.com/questions/6099467/how-to-parse-a-saml-assertion-request-in-net