公開日:2013年3月5日
最終更新日:2020年8月13日
最終更新日:2020年8月13日
CSRF の安全なトークンの作成方法(ASP.NET,C#,VB.NET編)
以下の記事の内容に従って、ASP.NET(C#, VB.NET) で CSRF の安全なトークンを作成する方法をご紹介します。
.NET の 暗号論的擬似乱数生成器 で乱数を作成できるクラスは、System. Security. Cryptography. RNGCryptoServiceProvider クラスになります。
また、安全なトークンの桁数は32桁になります。
・C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Security.Cryptography; namespace TestCS { public class Csrf { private static int TOKEN_LENGTH = 16; //16*2=32バイト //32バイトのCSRFトークンを作成 public static string GetCsrfToken() { byte[] token = new byte[TOKEN_LENGTH]; RNGCryptoServiceProvider gen = new RNGCryptoServiceProvider(); gen.GetBytes(token); StringBuilder buf = new StringBuilder(); for (int i = 0; i < token.Length; i++) { buf.AppendFormat("{0:x2}", token[i]); } return buf.ToString(); } } }
・VB.NET
Imports System.Security.Cryptography Public Class Csrf Private Shared TOKEN_LENGTH As Integer = 15 '16*2=32バイト' '32バイトのCSRFトークンを作成' Public Shared Function GetCsrfToken() As String Dim token As Byte() = New Byte(TOKEN_LENGTH) {} Dim gen As RNGCryptoServiceProvider = New RNGCryptoServiceProvider() gen.GetBytes(token) Dim buf As StringBuilder = New StringBuilder() For i As Integer = 0 To token.Length - 1 buf.AppendFormat("{0:x2}", token(i)) Next Return buf.ToString() End Function End Class
このクラスによって生成されたトークンは以下のようになります。
59246cdfc01e47f64d0cceaf13c6bac0
参考
Webアプリケーションセキュリティに関する記事は、以下のページにまとまっています。ぜひご確認ください。
スポンサーリンク
カテゴリー:Webアプリケーションセキュリティ対策
コメントを残す