Geo*_*hev 1 php delphi delphi-7
我试图在Delphi和PHP之间交换加密的消息.
从Delphi方面我从这里下载了DCPcrypt v2 Beta 3:
http://www.cityinthesky.co.uk/opensource/dcpcrypt/
对于加密我使用此功能:
function TForm1.Encrypt3DES(psData, psKey: string): string;
var
Cipher: TDCP_3des;
begin
Cipher:= TDCP_3des.Create(nil);
Cipher.InitStr(psKey,TDCP_sha256);
result:=Cipher.EncryptString(psData);
Cipher.Burn;
Cipher.Free;
end;
Run Code Online (Sandbox Code Playgroud)
我正在测试它:
ShowMessage(Encrypt3DES('test','SecretKeySecretKeySecret'));
Run Code Online (Sandbox Code Playgroud)
我得到的结果是Z74E0Q ==我可以使用另一个类似的delphi函数成功解密它:
function TForm1.Decrypt3DES(psData, psKey: string): string;
var
Cipher: TDCP_3des;
begin
Cipher:= TDCP_3des.Create(nil);
Cipher.InitStr(psKey, TDCP_sha256);
result:=Cipher.DecryptString(psData);
Cipher.Burn;
Cipher.Free;
end;
Run Code Online (Sandbox Code Playgroud)
从PHP端我试过几个功能相同的字符串("测试")使用相同的密钥("SecretKeySecretKeySecret")加密,但结果是什么,我在Delphi中得到不同的.我再次成功解密PHP中具有类似功能的消息,但我需要在Delphi中解密消息.
这是我在PHP中所做的,我甚至试图散列键,因为我看到Delphi函数正在使用TDCP_sha256,但结果仍然不同.
$key = "SecretKeySecretKeySecret";
echo base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, 'test', 'ecb')).'<BR><BR>';
echo openssl_encrypt('test', 'des-ede3', $key).'<BR><BR>';
$key = hash('sha256', $key);
echo openssl_encrypt('test', 'des-ede3', $key).'<BR><BR>';
Run Code Online (Sandbox Code Playgroud)
这是结果:
Z05z5Bp4/VY =
L5qmk5nJOzs =
bm7yRdrMs5g =
我究竟做错了什么?BTW我正在使用Delphi 7和DCPcrypt是目前唯一能够让它运行的库.
我认为这会对你有所帮助.TDCP_3des是块密码和EncryptString方法使用EncryptCFB8bit方法(使用CFB(8位)加密方法加密大小字节数据).
有两件事很重要:
德尔福部分:
function TForm1.Encrypt3DES(psData, psKey: string): string;
var
Cipher: TDCP_3des;
i: integer;
begin
Cipher := TDCP_3des.Create(nil);
try
Cipher.InitStr(psKey, TDCP_sha256);
Cipher.SetIV('00000000');
Result := Cipher.EncryptString(psData);
Cipher.Burn;
finally
Cipher.Free;
end{try};
end;
procedure TForm1.btnEncryptClick(Sender: TObject);
var
input, key: string;
begin
input := 'Some words in English';
key := 'SecretKeySecretKeySecret';
ShowMessage(Encrypt3DES(input, key));
end;
Run Code Online (Sandbox Code Playgroud)
PHP部分:
<?
$key = "SecretKeySecretKeySecret";
$key = hash('sha256', $key, true);
$key = substr($key, 0, 24);
$iv = '00000000';
$message = 'Some words in English';
$result = mcrypt_encrypt(MCRYPT_3DES, $key, $message, MCRYPT_MODE_CFB, $iv);
$result = base64_encode($result);
echo 'Input text: '.$message.'</br>';
echo 'Encrypted text: '.$result.'</br>';
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Input: Some words in English
Encrypted text: hTpdn+USolFTgv/4HnBEvo4scgmp
Input: This will test Delphi7 and PHP encryption.
Encrypted text: gik2Iw/m2rtMA9gdKqvFqDg3kuUSb4rnAieyZ8unIvt510Rbt1jLPO+/
Input: I hope this will work.
Encrypted text: n/JxW12zORaI7TSCAF4/6cBxqC3mZg==
Run Code Online (Sandbox Code Playgroud)
笔记:
使用Delphi 7,DCPcrypt v2,PHP 5.2.10,mcrypt 2.5.7进行测试.
| 归档时间: |
|
| 查看次数: |
452 次 |
| 最近记录: |