首页 > 解决方案 > PHP河豚加密字符串,如何在Lazarus中解密

问题描述

我在 PHP 中有代码使用河豚和 sha256 哈希加密字符串:

<?php
    $plaintext = "Secret text";
    $ivlen = openssl_cipher_iv_length($cipher="BF-CBC");
    $iv = '1234567812345678';
    $key = 'password';
    $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
    $ciphertext = base64_encode( $ciphertext_raw );
    echo "encrypted string:<br>$ciphertext2<br><br>";
?>

我在 Lazarus 中有用于解密此字符串的代码:

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, 
  DCPblowfish, DCPsha256, base64;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    DCP_blowfish1: TDCP_blowfish;
    DCP_sha256_1: TDCP_sha256;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private

  public

  end;

var
  Form1: TForm1;
  

implementation

{$R *.frm}

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
var
    Cipher: TDCP_blowfish;
    iv: string;
    KeyStr: string;
    encrypted_string: string;
    decrypted_string: string;
begin
    memo1.lines.clear;
    encrypted_string := 'text from php';
    KeyStr := 'password';   
    iv := '1234567812345678';
    Cipher := TDCP_blowfish.Create(Self);
    Cipher.InitStr(KeyStr, TDCP_sha256);        
    cipher.SetIV(iv);
    decrypted_string := Cipher.DecryptString(DecodeStringBase64(encrypted_string));
    memo1.lines.add(decrypted_string);
    Cipher.Burn;
    Cipher.Free;
    Dest.Free;
        
end;

end.

但是解密的字符串不是我所期望的:(我的错误在哪里?或者在 PHP 中使用河豚加密字符串并在 Lazarus 中解密(使用 DCPCrypt?)的最简单方法是什么?谢谢

更新:

我已将代码更改为使用文件而不是纯文本字符串 PHP:

<?php
    $plaintext = "secret";
    $ivlen = openssl_cipher_iv_length($cipher="BF-CBC");
    $iv = '12345678';
    $key = hash('sha256', 'password');
    $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
    file_put_contents('file.enc', $ciphertext_raw);
?>

拉撒路:

procedure TForm1.Button2Click(Sender: TObject);
var
    Cipher: TDCP_blowfish;
    Source, Dest: TFileStream;
    iv: string;
  begin
    stream:= TStream.create;
    KeyStr := 'password';
    iv := '12345678';
    Source:= TFileStream.Create('file.enc',fmOpenRead);   
        Dest:= TFileStream.Create(Edit2.Text,fmCreate);   
        Cipher := TDCP_blowfish.Create(Self);
        Cipher.InitStr(KeyStr,TDCP_sha256);    
        cipher.SetIV(iv);
        Cipher.DecryptStream(Source,Dest,Source.Size); 

        Cipher.Burn;
        Cipher.Free;
        Dest.Free;
        Source.Free;
  end;       

它仍然无法正常工作:(

标签: phpencryptionlazarusblowfish

解决方案


推荐阅读