Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Capicom Verify (https://www.clubdelphi.com/foros/showthread.php?t=86734)

shoulder 24-09-2014 02:17:33

Capicom Verify
 
Hola no logro encontrar en delphi la funcion del capicom para verificar si un pdf esta firmado. Encontre en VB pero no puedo hacerla funcionar en Delphi me da error
Código:

Unit capicom_tbl

SignedMessage =A string that contains the signed message to be verified.

SignedData.Verify( _  ByVal SignedMessage, _  [ ByVal bDetached ], _  [ ByVal VerifyFlag ] _ )

VerifyFlag  : CAPICOM_VERIFY_SIGNATURE_ONLY

Gracias

movorack 24-09-2014 03:05:37

En Google colocas "delphi capicom" y el primer enlace es este tutorial Uso de CAPICOM y Delphi para acceso a los certificados digitales

Oh! veneradísimo San Google que sería de nuestro existir sin tu excelentísimo algoritmo de búsqueda.

shoulder 24-09-2014 03:25:50

Capicom
 
Gracias de ahi pude obtener como leer los datos del token verificar datos, fecha de vencimiento..etc. Pero no hay nada sobre la verificacion de una firma en un pdf es la funcion que nombre en mi primer post y no lo puedo hacer funcionar en delphi.

nlsgarcia 24-09-2014 04:29:25

shoulder,

Cita:

Empezado por shoulder
...no logro en Delphi la función (Método) SignedData.Verify del CAPICOM para verificar si un pdf esta firmado...

:rolleyes:

Revisa este código:
Código Delphi [-]
 function TDigital_CAPICOM.VerifySign(const AFileName: string): Boolean;  
 var  
   SignedData: ISignedData;  
   HashString: WideString;  
   ASignedContent: string;  
 begin  
   Result := True;  
   try  
     GetCertificate;  
     //先获取签名信息,因为会做信息分离,还原出加上签名前的数据   
     ASignedContent:= ExtractSignedContent(AFileName);  
     //获取文件哈希值   
     HashString:= GetFileHash(AFileName);  
     //构建 数据签名对象   
     SignedData := CoSignedData.Create;  
     SignedData.Content := HashString;  
     //执行检查   
     SignedData.Verify(ASignedContent, False, CAPICOM_VERIFY_SIGNATURE_ONLY);  
   except  
     Result := False;  
     Raise Exception.Create('数字签名校验失败!');  
   end;  
 end;
Tomado de : delphi实现数字签名

Revisa esta información:
Espero sea útil :)

Nelson.

shoulder 24-09-2014 16:14:12

Capicom
 
Gracias habia probado con esa pagina integre las funciones y el procedimiento pero me da siempre error en HYMSignature, agregue la Unit Types para solucionar el error de TByteDynArray
Código Delphi [-]
 
function ExtractSignedContent(
  const AFileName: string): string;
var
  fs: TFileStream;
  iHeadLen, iContentLen, iPos: Integer;
  sContentLength: string;
  ms: TMemoryStream;
  BDA_Head, BDA_Cont: TByteDynArray;
begin
  Result := '';
  if not FileExists(AFileName) then
    raise Exception.Create('??"' + AFileName + '"???');
  iHeadLen := Length(HYMSignature) + HashString_Length;
  SetLength(BDA_Head, iHeadLen);
  ms:= TMemoryStream.Create;
  ms.LoadFromFile(AFileName);
  fs := TFileStream.Create(AFileName, fmCreate);
  try
    ms.Position:= 0;  
    ms.Read(BDA_Head[0], iHeadLen);  
    sContentLength := Byte2String(BDA_Head); //??????
    iPos := Pos(HYMSignature, sContentLength);  
    if iPos > 0 then  
    begin  
      //????
      iContentLen := StrToInt(Copy(sContentLength, Length(HYMSignature) + 1, MaxInt));
      SetLength(BDA_Cont, iContentLen);  
      ms.Read(BDA_Cont[0], iContentLen);  
      Result := Byte2String(BDA_Cont);  
      //??????????????
      fs.CopyFrom(ms, ms.Size - ms.Position); //?????????????
      fs.Position := 0;
    end
  finally
    ms.Free;
    fs.Free;
  end;
end;

function GetCertficateInfo(
  var ACertInfo: TStampInfo): Boolean;
var
  iCnt: Integer;
begin
  Result := True;
  if ICert <> nil then
  begin
    ACertInfo.PKAlg := FAlgType;
    ACertInfo.PKLength := FPKLength;
    for iCnt := 0 to Length(FPublicKey) - 1 do
    begin
      ACertInfo.PKContent[iCnt] := FPublicKey[iCnt + 1];
    end;
    ACertInfo.EndDate:= ICert.ValidToDate;
    ACertInfo.DispachTime:= ICert.ValidFromDate;
  end
  else  
    result:= False;
end;


function VerifySign(const AFileName: string): Boolean;
 var
   SignedData: ISignedData;
   HashString: WideString;
   ASignedContent: string;
 begin
   Result := True;
   try
     GetCertificate;

     ASignedContent:= ExtractSignedContent(AFileName);

     HashString:= GetFileHash(AFileName);

     SignedData := CoSignedData.Create;
     SignedData.Content := HashString;  

     SignedData.Verify(ASignedContent, False, CAPICOM_VERIFY_SIGNATURE_ONLY);
   except  
     Result := False;  
     Raise Exception.Create('????????!');
   end;
 end;

procedure form33.GetCertificate;
var
  vStore: TStore;
  iCnt: Integer;
  BaseIntf: IInterface;
  ICert2Dsp: ICertificate2Disp;
begin
  if ICert2 = nil then
  begin
    vStore := OpenStore(FStoreName);
    for iCnt := 1 to vStore.Certificates.Count do
    begin
      IBaseIntf := vStore.Certificates.Item[iCnt];
      try
        if IBaseIntf.QueryInterface(ICertificate2Disp, ICert2Dsp) = 0
        then
        begin
          //????????
          if ICert2Dsp.HasPrivateKey then
          begin
            //???????CSP???
            if ((FProviderName = CSPProvider_ePass) and
                ((ICert2Dsp.PrivateKey.ProviderName = CSPProvider_ePass_1K) or
                 (ICert2Dsp.PrivateKey.ProviderName = CSPProvider_ePass_3K)))
               or (ICert2Dsp.PrivateKey.ProviderName = FProviderName)  
            then  
            begin
              IBaseIntf.QueryInterface(IID_ICertificate2, ICert2);  
              IBaseIntf.QueryInterface(IID_ICertificate, ICert);  
              FPublicKey:= ICert2Dsp.publickey.EncodedKey.Format(True);  
              FPKLength:= ICert2Dsp.publickey.Length;
              FAlgType:= ICert2Dsp.publickey.Algorithm.FriendlyName;  
            end;  
          end;  
        end;  
      except
        //?????CAPICOM?,?????   
        ICert2 := nil;  
      end;  
    end;  
  end;
end;

shoulder 24-09-2014 21:58:01

Capicom
 
Tampoco funciona, me da no declarado TSignedData

Código Delphi [-]
function TfrmPrincipal.verificaassdigital(pathArquivo: string): boolean; 
var 
  lSignedData: TSignedData;      // undeclared indentifier 
  fs : TFileStream; 
  qt : integer; 
  ch : PWideChar; 
  msg : WideString; 
  ok : boolean; 
begin 
  fs := TFileStream.Create (edMsgFile.Text, fmOpenRead); 
  New (ch); 
  repeat 
    qt := fs.Read(ch^, 2); 
    if qt > 0 then 
    msg := msg + ch^; 
  until qt = 0; 
  fs.Free; 
  Dispose (ch); 
 
  lSignedData := TSignedData.Create(self); 
 
  try 
    ok := false; 
    lSignedData.Verify (msg, false, CAPICOM_VERIFY_SIGNATURE_ONLY); 
    msg := lSignedData.Content; 
    ok := true; 
  except 
  on exc: Exception do 
  ShowMessage (exc.Message); 
  end; 
 
  lSignedData.Free; 
 
  if ok then 
    ShowMessage ('Conteúdo validado com sucesso !'); 
  end;

shoulder 24-09-2014 22:07:00

Capicom
 
Tampoco funciona, me da no declarado TSignedData

Código Delphi [-]
function TfrmPrincipal.verificaassdigital(pathArquivo: string): boolean; 
var 
  lSignedData: TSignedData;      // undeclared indentifier 
  fs : TFileStream; 
  qt : integer; 
  ch : PWideChar; 
  msg : WideString; 
  ok : boolean; 
begin 
  fs := TFileStream.Create (edMsgFile.Text, fmOpenRead); 
  New (ch); 
  repeat 
    qt := fs.Read(ch^, 2); 
    if qt > 0 then 
    msg := msg + ch^; 
  until qt = 0; 
  fs.Free; 
  Dispose (ch); 
 
  lSignedData := TSignedData.Create(self); 
 
  try 
    ok := false; 
    lSignedData.Verify (msg, false, CAPICOM_VERIFY_SIGNATURE_ONLY); 
    msg := lSignedData.Content; 
    ok := true; 
  except 
  on exc: Exception do 
  ShowMessage (exc.Message); 
  end; 
 
  lSignedData.Free; 
 
  if ok then 
    ShowMessage ('Conteúdo validado com sucesso !'); 
  end;

shoulder 25-09-2014 16:52:36

Verify
 
Encontre este procedimiento lo hice funcionar pero me da siempre No se pudo comprobar el fabricante, desea ejeutar igual este sof....pulso ejecutar no hace nada y me cambia toda la pantalla de color.

Código Delphi [-]
const
  WTD_UI_ALL    = 1;
  WTD_UI_NONE   = 2;
  WTD_UI_NOBAD  = 3;
  WTD_UI_NOGOOD = 4;

  WTD_REVOKE_NONE       = $00000000;
  WTD_REVOKE_WHOLECHAIN = $00000001;

  WTD_CHOICE_FILE    = 1;
  WTD_CHOICE_CATALOG = 2;
  WTD_CHOICE_BLOB    = 3;
  WTD_CHOICE_SIGNER  = 4;
  WTD_CHOICE_CERT    = 5;

  WTD_STATEACTION_IGNORE           = $00000000;
  WTD_STATEACTION_VERIFY           = $00000001;
  WTD_STATEACTION_CLOSE            = $00000002;
  WTD_STATEACTION_AUTO_CACHE       = $00000003;
  WTD_STATEACTION_AUTO_CACHE_FLUSH = $00000004;

type
  PWinTrustFileInfo = ^TWinTrustFileInfo;
  TWinTrustFileInfo = record
    cbStruct: DWORD;
    pcwszFilePath: PWideChar;
    hFile: THandle;
    pgKnownSubject: PGUID;
  end;

  PWinTrustData = ^TWinTrustData;
  TWinTrustData = record
    cbStruct: DWORD;
    pPolicyCallbackData: Pointer;
    pSIPClientData: Pointer;
    dwUIChoice: DWORD;
    fdwRevocationChecks: DWORD;
    dwUnionChoice: DWORD;
    pUnionData: Pointer;
    dwStateAction: DWORD;
    hWVTStateData: THandle;
    pwszURLReference: PWideChar;
    dwProvFlags: DWORD;
    dwUIContext: DWORD;
  end;

function VerifySignature(const FileName: WideString): Longint;
var
  FileInfo: TWinTrustFileInfo;
  TrustData: TWinTrustData;
begin
  FillChar(FileInfo, SizeOf(FileInfo), 0);
  FileInfo.cbStruct := SizeOf(FileInfo);
  FileInfo.pcwszFilePath := PWideChar(FileName);

  FillChar(TrustData, SizeOf(TrustData), 0);
  TrustData.cbStruct := SizeOf(TrustData);
  TrustData.dwUIChoice := WTD_UI_NONE;
  TrustData.fdwRevocationChecks := WTD_REVOKE_NONE;
  TrustData.dwUnionChoice := WTD_CHOICE_FILE;
  TrustData.pUnionData := @FileInfo;
  TrustData.dwStateAction := WTD_STATEACTION_IGNORE;
  TrustData.dwProvFlags := WTD_SAFER_FLAG;
  TrustData.dwUIContext := WTD_UICONTEXT_EXECUTE;

  Result := WinVerifyTrust(0, WINTRUST_ACTION_GENERIC_VERIFY_V2, @TrustData);
end;
Código Delphi [-]
procedure CodeSignVerify(const FileName: string; AllowUserPrompt: Boolean = False);
var
  SignedCode: ISignedCode;
begin
  SignedCode := CoSignedCode.Create;
  SignedCode.FileName := FileName;
  SignedCode.Verify(AllowUserPrompt);
end;

shoulder 26-09-2014 16:47:02

Verify
 
Aparentemente este codigo funciona, lo que no se como hacer como se extrae el Exit Code, el mensaje que me brinda java?-
Código Delphi [-]
Primero := ' -jar  "C:\Archivos de programa\JSignPdf\JSignPdf.jar"  '
           + 'jar -c "signer.crt;tsa.crt" document_signed.pdf '';

Process := ExecuteProcess('C:\Archivos de programa\JSignPdf\jre\bin\javaw.exe' + pchar(primero));

if Process <> 0 then
   WaitForSingleObject(Process, INFINITE);


La franja horaria es GMT +2. Ahora son las 11:04:03.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi