⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mainform.cpp

📁 著名的SecureBlackBox控件完整源码
💻 CPP
字号:
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "MainForm.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "SBPDF"
#pragma link "SBPDFSecurity"
#pragma link "SBX509"
#pragma resource "*.dfm"
TfrmMain *frmMain;
//---------------------------------------------------------------------------
__fastcall TfrmMain::TfrmMain(TComponent* Owner)
        : TForm(Owner)
{
  SetLicenseKey((AnsiString)
  "ADDCD14AD06709806817E0B3D7BFD0A2222D536FE156466C5D5FE65DB5DEAE76" + 
  "FFDEBC07E915A5751C12C01C783958872A38E4A5EDA140E7247E0F2E56442A3C" + 
  "F3E9347AD8FDE52083A0DFC86BC00ECB0FD0CF1B51159A2BCB84F6EA6349EF47" + 
  "5C15A59AFCC55F7C3AAD26C279628B5D91B1DC94BD2385354A70CCA3B76101D9" + 
  "F41C84A639FC3CCE4BA8F0CC4A66DCD150114A3F58C1AD46B7B94643741BC20A" + 
  "8DCA83AB921480951B423CAA19EF1863A47CA2C3422E7E5634BED98939A5AE43" + 
  "DE1E4BAD79E66D8A5C973B3455656C8C9B6FF024FADD6CDA02D0F506D98493C8" + 
  "BD1ED7B237DB75FA31F2C82654490CDDDEE24E19939137B9E1DB05508733B22F");
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnBrowseSourceClick(TObject *Sender)
{
    if (OpenDialogPDF->Execute())
        editSource->Text = OpenDialogPDF->FileName;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnBrowseDestClick(TObject *Sender)
{
    if (SaveDialogPDF->Execute())
        editDest->Text = SaveDialogPDF->FileName;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::rbPasswordEncryptionClick(TObject *Sender)
{
    editPassword->Enabled = true;
    editCert->Enabled = false;
    editCertPassword->Enabled = false;
    lCertificate->Enabled = false;
    lCertPassword->Enabled = false;
    btnBrowseCert->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::rbPublicKeyEncryptionClick(TObject *Sender)
{
    editPassword->Enabled = false;
    editCert->Enabled = true;
    editCertPassword->Enabled = true;
    lCertificate->Enabled = true;
    lCertPassword->Enabled = true;
    btnBrowseCert->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnBrowseCertClick(TObject *Sender)
{
    if (OpenDialogCert->Execute())
        editCert->Text = OpenDialogCert->FileName;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnCancelClick(TObject *Sender)
{
    Close();
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnEncryptClick(TObject *Sender)
{
    // creating a temporary file copy
    AnsiString TempPath = GenerateTempFilename();

    if (!CopyFile(editSource->Text.c_str(), TempPath.c_str(), false))
    {
        MessageDlg("Failed to create a temporary file", mtError, TMsgDlgButtons()<<mbOK, 0);
        return;
    }
    // opening the temporary file
    bool Success = false;
    TFileStream* F = new TFileStream(TempPath, fmOpenReadWrite | fmShareDenyWrite);
    try
    {
        try
        {
            // opening the document
            Document->Open(F);
            try
            {
                // checking if the document is already encrypted
                if (Document->Encrypted)
                {
                    MessageDlg("The document is already encrypted", mtError, TMsgDlgButtons()<<mbOK, 0);
                    return;
                }
                // setting up property values
                TElPDFSecurityHandler* CurrHandler;
                if (rbPasswordEncryption->Checked)
                    CurrHandler = PasswordHandler;
                else
                    CurrHandler = PublicKeyHandler;
                // the following encryption handler assignment must be executed before
                // other handler properties are assigned, since encryption handler
                // has to access document properties during its work.
                Document->EncryptionHandler = CurrHandler;
                CurrHandler->EncryptMetadata = cbEncryptMetadata->Checked;
                int Alg;
                int KeySize;
                switch (cbAlgorithm->ItemIndex)
                {
                    case 0:
                        Alg = SB_ALGORITHM_CNT_RC4;
                        KeySize = 40;
                        break;
                    case 1:
                        Alg = SB_ALGORITHM_CNT_RC4;
                        KeySize = 128;
                        break;
                    case 2:
                        Alg = SB_ALGORITHM_CNT_AES128;
                        // the key size for this cipher is always 128 bits, so we may
                        // omit the assignment in this point. However, just to calm the
                        // compiler we assing the 0 value to KeySize variable.
                        KeySize = 0;
                        break;
                    default:
                        // normally, we should not reach this point, so just making the
                        // compiler silent.
                        MessageDlg("Unsupported algorithm", mtError, TMsgDlgButtons()<<mbOK, 0);
                        return;
                }
                // PDF specification allows to use different ciphers for streams and
                // strings contained in a document. However, using the same value for
                // both string and stream encryption allows to achieve greater compatibility
                // with other implementations
                CurrHandler->StreamEncryptionAlgorithm = Alg;
                CurrHandler->StringEncryptionAlgorithm = Alg;
                CurrHandler->StreamEncryptionKeyBits = KeySize;
                CurrHandler->StringEncryptionKeyBits = KeySize;
                if (AnsiString(CurrHandler->ClassName()) == "TElPDFPasswordSecurityHandler")
                {
                    PasswordHandler->UserPassword = editPassword->Text;
                    PasswordHandler->OwnerPassword = editPassword->Text;
                    PasswordHandler->Permissions->EnableAll();
                }
                else
                {
                    // loading certificate
                    TFileStream* CertF = new TFileStream(editCert->Text, fmOpenRead | fmShareDenyWrite);
                    try
                    {
                        TSBCertFileFormat CertFormat = Cert->DetectCertFileFormat(NULL,CertF);
                        CertF->Position = 0;
                        switch (CertFormat)
                        {
                            case cfDER :
                                Cert->LoadFromStream(CertF,CertF->Size);
                                break;
                            case cfPEM:
                                Cert->LoadFromStreamPEM(CertF, editCertPassword->Text, CertF->Size);
                                break;
                            case cfPFX:
                                Cert->LoadFromStreamPFX(CertF, editCertPassword->Text, CertF->Size);
                                break;
                            default:
                                MessageDlg("Failed to load certificate", mtError, TMsgDlgButtons()<<mbOK, 0);
                                return;
                        }
                    }
                    __finally
                    {
                        delete CertF;
                    }
                    // creating recipient group
                    int GroupIndex = PublicKeyHandler->AddRecipientGroup();
                    // adding recipient certificate to group
                    PublicKeyHandler->RecipientGroups[GroupIndex]->AddRecipient(Cert);
                    PublicKeyHandler->RecipientGroups[GroupIndex]->Permissions->EnableAll();
                }
                // encrypting the document
                Document->Encrypt();
                // allowing to save the document
                Success = true;
            }
            __finally
            {
              // closing the document
              Document->Close(Success);
            }
        }
        __finally
        {
            delete F;
        }
    }
    catch(Exception &e)
    {
        MessageDlg((AnsiString)"Error: " + e.Message, mtError, TMsgDlgButtons()<<mbOK, 0);
        Success = false;
    }

    // if encryption process succeeded, moving the temporary file to the place
    // of destination file
    if (Success)
    {
        if (!CopyFile(TempPath.c_str(), editDest->Text.c_str(), false))
            MessageDlg("Failed to save temporary file", mtError, TMsgDlgButtons()<<mbOK, 0);
        else
            MessageDlg("Encryption process successfully finished", mtInformation, TMsgDlgButtons()<<mbOK, 0);
    }
    else
        MessageDlg("Encryption failed", mtError, TMsgDlgButtons()<<mbOK, 0);
    // deleting temporary file
    DeleteFile(TempPath);
    Close();
}
//---------------------------------------------------------------------------
AnsiString TfrmMain::GenerateTempFilename(void)
{
    const char* szSBB = "sbb";
    DWORD dwNeeded = GetTempPathA(0, NULL);
    char* szPath = new char[dwNeeded+1];
    dwNeeded = GetTempPathA(dwNeeded, szPath);
    if (dwNeeded == 0)
    {
        delete[] szPath;
        throw(Exception("Failed to get temporary path"));
    }
    char* szResult = new char[MAX_PATH];
    if (GetTempFileNameA(szPath, szSBB, 0, szResult) == 0)
    {
        delete[] szPath;
        delete[] szResult;
        throw(Exception("Failed to generate a temporary file name"));
    }

    AnsiString sResult = AnsiString(szResult);
    delete[] szPath;
    delete[] szResult;
    return sResult;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::FormCreate(TObject *Sender)
{
    cbAlgorithm->ItemIndex = 0;
}
//---------------------------------------------------------------------------

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -