<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Horn Network &#187; DESCryptoServiceProvider</title>
	<atom:link href="http://klcin.tw/net/tag/descryptoserviceprovider/feed" rel="self" type="application/rss+xml" />
	<link>http://klcin.tw/net</link>
	<description>Horn Network (.NET, ASP.NET, C#, VB.NET, CSS, JavaScript, Ubuntu, PDA, Windows Mobile ...)</description>
	<lastBuildDate>Sat, 10 Jul 2010 14:44:08 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>在 WebService 用 SoapHeader 傳遞認證資訊並用 DESCryptoServiceProvider 加解密</title>
		<link>http://klcin.tw/net/webservice-soapheader-descryptoserviceprovider</link>
		<comments>http://klcin.tw/net/webservice-soapheader-descryptoserviceprovider#comments</comments>
		<pubDate>Thu, 02 Apr 2009 08:21:40 +0000</pubDate>
		<dc:creator>klcintw</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Web Service]]></category>
		<category><![CDATA[DESCryptoServiceProvider]]></category>
		<category><![CDATA[UserHeaderValue]]></category>
		<category><![CDATA[WebService]]></category>

		<guid isPermaLink="false">http://klcin.tw/net/?p=122</guid>
		<description><![CDATA[本文介紹：在 WebService 用 SoapHeader 傳遞認證資訊並用 DESCryptoServiceProvider 加解密。
SoapHeader 變數圖解：    
 
程式碼
SoapHeader

public class UserHeader : System.Web.Services.Protocols.SoapHeader
{
  public UserHeader() {}

  public string Username { get { return m_Username; } set { m_Username = value; } }
  private string m_Username;

  public string Password { get { return m_Password; } set { m_Password [...]]]></description>
			<content:encoded><![CDATA[<p><strong>本文介紹</strong>：在 WebService 用 SoapHeader 傳遞認證資訊並用 DESCryptoServiceProvider 加解密。</p>
<p>SoapHeader 變數圖解：   <br /><a href="http://klcin.tw/net/wp-content/uploads/2009/04/snap250.png"><img title="SoapHeader 變數圖解" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="249" alt="SoapHeader 變數圖解" src="http://klcin.tw/net/wp-content/uploads/2009/04/snap250-thumb.png" width="404" border="0" /></a> </p>
<p> <span id="more-122"></span><br />
<h2>程式碼</h2>
<h3>SoapHeader</h3>
<p>
<pre class="brush: c#">public class UserHeader : System.Web.Services.Protocols.SoapHeader
{
  public UserHeader() {}

  public string Username { get { return m_Username; } set { m_Username = value; } }
  private string m_Username;

  public string Password { get { return m_Password; } set { m_Password = value; } }
  private string m_Password;
}</pre>
</p>
<h3>WebService</h3>
<p>
<pre class="brush: c#">// using System.Web.Services.Protocols;

public UserHeader m_userHeader = null;
public UserHeader UserHeader
{
  get { return m_userHeader; }
  set { m_userHeader = value; }
}

[SoapHeader(&quot;UserHeader&quot;, Direction = SoapHeaderDirection.InOut)]
[WebMethod]
public string ReturnLoginUser()
{
  string msg = &quot;err&quot;;
  if (m_userHeader != null)
  {
    string name = Decrypt(m_userHeader.Username, m_Key, m_IV);
    string pwd = Decrypt(m_userHeader.Password, m_Key, m_IV);

    msg = name + &quot;|&quot; + pwd;
  } // if

  return msg;
}</pre>
</p>
<h3>Client</h3>
<p>
<pre class="brush: c#">static void Main(string[] args)
{
  Service ws = new Service();

  string key=&quot;&quot;, iv=&quot;&quot;;
  ws.GetKeyAndIv(ref key, ref iv);

  UserHeader uh = new UserHeader();
  uh.Username = Encrypt(&quot;中文(abc)&quot;, key, iv);
  uh.Password = Encrypt(&quot;1234-ABC&quot;, key, iv);

  ws.UserHeaderValue = uh;
  Console.WriteLine(&quot;Return:{0}&quot;, ws.ReturnLoginUser());
  Console.ReadKey();
}</pre>
</p>
<h3>加密</h3>
<p>
<pre class="brush: c#">/// &lt;summary&gt;
/// DEC 加密法
/// &lt;/summary&gt;
/// &lt;param name=&quot;txt&quot;&gt;加密文本&lt;/param&gt;
/// &lt;param name=&quot;sKey&quot;&gt;加密金鑰&lt;/param&gt;
/// &lt;param name=&quot;sIV&quot;&gt;初始化向量&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public static string Encrypt(string txt, string key, string iv)
{
  System.Text.StringBuilder ret = new System.Text.StringBuilder();
  using (System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider())
  {
    byte[] data = System.Text.Encoding.Default.GetBytes(txt);
    des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
    des.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv);

    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
      using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
      {
         cs.Write(data, 0, data.Length);
         cs.FlushFinalBlock();
      } // using

      foreach (byte b in ms.ToArray())
     {
        ret.AppendFormat(&quot;{0:X2}&quot;, b);
     } // foreach
    } // using
  } // using

  return ret.ToString();
}</pre>
</p>
<h3>解密</h3>
<p>
<pre class="brush: c#">/// &lt;summary&gt;
/// DEC 解密法
/// &lt;/summary&gt;
/// &lt;param name=&quot;txt&quot;&gt;解密的字串&lt;/param&gt;
/// &lt;param name=&quot;sKey&quot;&gt;加密金鑰&lt;/param&gt;
/// &lt;param name=&quot;sIV&quot;&gt;初始化向量&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public static string Decrypt(string txt, string key, string iv)
{
  using (System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider())
  {
    byte[] data = new byte[txt.Length / 2];
    for (int x = 0; x &lt; txt.Length / 2; x++)
    {
      int i = (Convert.ToInt32(txt.Substring(x * 2, 2), 16));
      data[x] = (byte)i;
    } // for

    des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
    des.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv);

    using (System.IO.MemoryStream ms =
      new System.IO.MemoryStream())
    {
      using (System.Security.Cryptography.CryptoStream cs =new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(),System.Security.Cryptography.CryptoStreamMode.Write))
      {
        try
        {
          cs.Write(data, 0, data.Length);
          cs.FlushFinalBlock();
          return System.Text.Encoding.Default.GetString(ms.ToArray());
        } // try
        catch
        {
          return &quot;&quot;;
        } // catch
      } // using
    } // using
  } // using
}</pre>
</p>
<p>&#160;</p>
<h4>檔案下載：</h4>
<ul>
<li><a hrerf='http://www.box.net/shared/y4cx0dk4k4' target='_blank'>程式碼（Box.net）</a></li>
</ul>
<h4>參考資料：</h4>
<ul>
<li>[MSDN] <a href="http://msdn.microsoft.com/zh-tw/library/system.web.services.protocols.soapheader(VS.80).aspx" target="_blank">SoapHeader 類別 (System.Web.Services.Protocols)</a></li>
<li>[MSDN] <a href="http://msdn.microsoft.com/zh-tw/library/system.security.cryptography.descryptoserviceprovider(VS.80).aspx" target="_blank">DESCryptoServiceProvider 類別 (System.Security.Cryptography)</a></li>
<li><a href="http://www.dotblogs.com.tw/dotjum/archive/2008/09/15/5379.aspx" target="_blank">[ASP.NET]為WebService多加上認證(SoapHeader) &#8211; Dotjum的分享空間</a>- 點部落</li>
<li><a href="http://www.dotblogs.com.tw/phoenix7765/archive/2008/08/30/5254.aspx" target="_blank">C# 加密(Encrypt) 解密(Decrypt) 使用DESCryptoServiceProvider &#8211; Phoenix.net 迷之殿</a>- 點部落</li>
<li><a href="http://www.cnblogs.com/Hetter/archive/2009/03/31/1426065.html" target="_blank">webservice 用戶驗證 加密 &#8211; Hetter</a> &#8211; 博客園</li>
<li><a href="http://www.cnblogs.com/jackyrong/archive/2007/05/23/757708.html" target="_blank">asp.net 2.0中傻瓜式使用soap header &#8211; jackyrong</a> &#8211; 博客園</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://klcin.tw/net/webservice-soapheader-descryptoserviceprovider/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
