「machineKey を設定する」の編集履歴(バックアップ)一覧に戻る

machineKey を設定する - (2008/02/04 (月) 19:44:42) のソース

// 現在のページ名
*&this_page() 

**概要

machineKey を設定し、webサイトの viewState を暗号化する。

参照:
-[[.NET Framework 一般リファレンス / machineKey 要素 (ASP.NET 設定スキーマ)>>http://msdn2.microsoft.com/ja-jp/library/w8h3skw9(VS.80).aspx]]

元ネタ:
-[[@IT総合トップ / テクノロジー / Insider.NET / .NETエンタープライズWebアプリケーション開発技術大全 / Webアプリケーションの状態管理>>http://www.atmarkit.co.jp/fdotnet/entwebapp/entwebapp03/entwebapp03_03.html]]

**前提条件
-[[新しいwebサイトの作成]]

**手順
default.aspx.vb を以下のように変更。

#highlight(vb.net){
Imports System.Security.Cryptography

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Response.Write("validationKey:")
        Response.Write("<br>")
        Response.Write(func_random(63))
        Response.Write("<br>")
        Response.Write("<br>")
        Response.Write("decryptionKey:")
        Response.Write("<br>")
        Response.Write(func_random(23))
        Response.Write("<br>")

    End Sub

    Protected Function func_random(ByVal length As Integer)

        Dim random() As Byte = New Byte(length) {}
        Dim rng As RNGCryptoServiceProvider = New RNGCryptoServiceProvider()
        rng.GetBytes(random)
        Dim s As String = ""
        Dim b As Byte
        For Each b In random : s += b.ToString("x2") : Next
        s = s.ToUpper()

        Return s

    End Function

End Class
}

実行すると以下のように表示される。
なお、実行する毎に結果文字列が変化する。

&img(234.jpg)

上記の結果文字列をメモ帳等に保存しておき、
web.config に以下を追加する。

#highlight(xml){
<configuration>
  <system.web>
    <machineKey validationKey="「結果文字列1」"
                decryptionKey="「結果文字列2」"
                validation="SHA1"/>
  </system.web>
</configuration>
}

&img(232.jpg)
記事メニュー
ウィキ募集バナー