using GenjiDotNet;

namespace NetCoreSample
{
    public partial class SigForm : Form
    {
        GenjiDotNet.API api;

        public SigForm(GenjiDotNet.API api_)
        {
            InitializeComponent();
            api = api_;
        }

        private void btnSignature_Click(object sender, EventArgs e)
        {
            try
            {
                if (DataText.Text.Trim().Length == 0)
                {
                    MessageBox.Show("テキストが空です");
                    return;
                }

                api.Init();
                api.Count();

                byte[] byteData = System.Text.Encoding.UTF8.GetBytes(DataText.Text);

                byte[] sig = new byte[128 + 1];
                short sigLen = 128 + 1;
                api.SignDataRSA(1234, 1, byteData, (short)byteData.Length, sig, ref sigLen, 1);

                byte[] sig1 = new byte[sigLen];
                System.Buffer.BlockCopy(sig, 0, sig1, 0, sigLen);

                string hexString = Convert.ToHexString(sig1);
                SigText.Text = hexString;

            }
            catch (APIException ex)
            {
                if (ex.Message == "Count" && ex.errorNo == 0)
                    MessageBox.Show("Genjiが見つかりません");
                else
                    MessageBox.Show(ex.Message + ":" + ex.errorNo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message );
            }

            api.Release();
        }

        private void btnVerify_Click(object sender, EventArgs e)
        {
            try
            {
                if (DataText.Text.Trim().Length == 0)
                {
                    MessageBox.Show("テキストが空です");
                    return;
                }

                if (SigText.Text.Trim().Length == 0)
                {
                    MessageBox.Show("署名が空です");
                    return;
                }

                api.Init();
                api.Count();


                byte[] byteData = System.Text.Encoding.UTF8.GetBytes(DataText.Text);
                byte[] byteSig = Convert.FromHexString(SigText.Text);

                api.VerifySigRSA(1234, 1, byteData, (short)byteData.Length, byteSig, (short)byteSig.Length, 1);
                MessageBox.Show("署名検証成功");
            }
            catch (APIException ex)
            {
                if (ex.Message == "Count" && ex.errorNo == 0)
                    MessageBox.Show("Genjiが見つかりません");
                else if (ex.Message == "VerifyDataRSA" && ex.errorNo == 0)
                    MessageBox.Show("署名検証失敗");
                else
                    MessageBox.Show(ex.Message + ":" + ex.errorNo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            api.Release();
        }
    }
}
