using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;
using System.IO;

public partial class PostAuth : System.Web.UI.Page
{
    const string hashKey = "vT4500$%&esx@sgfsasllg";

  // UNIXエポックを表すDateTimeオブジェクトを取得
  private static DateTime UNIX_EPOCH = 
    new DateTime(1970, 1, 1, 0, 0, 0, 0);

  public static long GetUnixTime(DateTime targetTime)
  {
    // UTC時間に変換
    targetTime = targetTime.ToUniversalTime();

    // UNIXエポックからの経過時間を取得
    TimeSpan elapsedTime = targetTime - UNIX_EPOCH;
    
    // 経過秒数に変換
    return (long)elapsedTime.TotalSeconds;
  }
    
    private static byte[] HashHMAC(byte[] key, byte[] message)
    {
        var hash = new HMACSHA256(key);
        return hash.ComputeHash(message);
    }

    private void createAuthFile(string strFileName, string strIP, string proxyUser, string webAppUser)
    {
        if (File.Exists(strFileName) == false)
        {
            using (FileStream hStream = System.IO.File.Create(strFileName))
            {
                if (hStream != null)
                {
                    hStream.Close();
                }
            }
        }

        using (StreamWriter w = new StreamWriter(strFileName, false))
        {
            w.WriteLine(strIP);
            w.WriteLine(proxyUser);
            w.WriteLine(webAppUser);
        }

    }

    public static string ToHexString(byte[] bytes)
    {
        StringBuilder sb = new StringBuilder(bytes.Length * 2);
        foreach (byte b in bytes)
        {
            if (b < 16) sb.Append('0'); // 二桁になるよう0を追加
            sb.Append(Convert.ToString(b, 16));
        }
        return sb.ToString();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // 
        // USBキー認証サーバからのキー情報を受け取り
        // 対応ユーザを取得した
        //

        // 乱数生成
        byte[] randoms = new byte[100];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randoms);

        //現在のUnixTime取得
        DateTime targetTime = DateTime.Now; 
        long unixTime = GetUnixTime(targetTime);

        // 乱数とUnixTimeから HMACハッシュを生成
        string message = unixTime.ToString() + System.Convert.ToBase64String(randoms);
        byte[] hash = HashHMAC( Encoding.Unicode.GetBytes(hashKey), Encoding.Unicode.GetBytes(message) );

        auth_token.Text = ToHexString(hash);
        TextBox1.Text = message;

        string strIP = Request.ServerVariables["REMOTE_ADDR"];

        createAuthFile(@"C:\customAuth\" + auth_token.Text, strIP, "proxyUser", "webAppUser");

        Response.Cookies["LoginToken"].Value = auth_token.Text;

        Response.Redirect("/site1/");
    }

}