using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace PTMedicalInsurance.Common.SMLib
{
    class VerifyPasswordEncryptUtils
    {
        public static string encrypt(string plaintext, string secKey)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(secKey);
            if (keyBytes.Length != 16)
                throw new ArgumentException("Key must be 16 bytes (ASCII string of length 16).");

            // 生成随机 IV（16 字节）
            byte[] iv = new byte[16];
            using (var rng = RandomNumberGenerator.Create())
                rng.GetBytes(iv);

            byte[] plainBytes = Encoding.UTF8.GetBytes(plaintext);

            // 使用 SM4/CBC/PKCS7
            var keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
            var ivParam = new ParametersWithIV(keyParam, iv);
            var cipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7Padding");
            cipher.Init(true, ivParam); // true = encrypt

            byte[] encrypted = cipher.DoFinal(plainBytes);

            // 拼接 IV + 密文
            byte[] combined = new byte[iv.Length + encrypted.Length];
            Buffer.BlockCopy(iv, 0, combined, 0, iv.Length);
            Buffer.BlockCopy(encrypted, 0, combined, iv.Length, encrypted.Length);

            // 返回 Base64（与 Java 一致）
            return Convert.ToBase64String(combined);
        }

        
    }
}
