using System; using System.Data; using System.IO; using System.Text; using GB5Shared.Connection; using FrameworkDAL.DTO.PDFEncrypt; using FrameworkDAL.Query.PDFEncrypt; using GB5Shared.DTO.Framework.Login; using GB5Shared.QueryExecutor; using iText.Kernel.Pdf; using static GB5Shared.GB5Constant.Constant; namespace FrameworkDAL.CustomCode.PDFEncrypt { public class PDFEncryptDAL : IPDFEncryptDAL { private readonly IQueryExecutor _queryExecutor; private readonly IApplicationConnection _IApplicationConnection; public PDFEncryptDAL(IQueryExecutor queryExecutor , IApplicationConnection IApplicationConnection) { _queryExecutor = queryExecutor; _IApplicationConnection = IApplicationConnection; } public async Task EncryptPdfBase64(string Base64Pdf, LoginDTO loginDTO) { try { string query = loginDTO.DatabaseType == DBType.SQL ? PDFEncryptQB.GETEMPSECRETKEY_SQL : PDFEncryptQB.GETEMPSECRETKEY_PG; PDFEncryptDTO pdfEncryptDTO = await _queryExecutor.QuerySingleAsync( loginDTO, query, new Dictionary { { "usercode", loginDTO.UserCode } } ); // Convert Base64 → byte[] byte[] inputPdfBytes = Convert.FromBase64String(Base64Pdf); if (pdfEncryptDTO == null || string.IsNullOrWhiteSpace(pdfEncryptDTO.SecretKey)) { return Base64Pdf; // No password, open directly } string UserPassword = _IApplicationConnection.Decrypt(pdfEncryptDTO.SecretKey, "GB5"); using var inputStream = new MemoryStream(inputPdfBytes); using var outputStream = new MemoryStream(); var writerProps = new WriterProperties() .SetStandardEncryption( Encoding.UTF8.GetBytes(UserPassword), Encoding.UTF8.GetBytes(UserPassword), EncryptionConstants.ALLOW_COPY, EncryptionConstants.ENCRYPTION_AES_256 ); using var reader = new PdfReader(inputStream); using var writer = new PdfWriter(outputStream, writerProps); using var pdfDoc = new PdfDocument(reader, writer); pdfDoc.Close(); return Convert.ToBase64String(outputStream.ToArray()); } catch (Exception) { throw; } } } }