Lockbox3 encryptstring:相同的字符串给出不同的加密结果

时间:2016-02-07 04:12:01

标签: delphi cryptography aes lockbox-3

我尝试使用Delphi XE10的lockbox3。 我想加密用户的输入字符串,并将其与验证值进行比较。但每次相同的输入字符串给出不同的加密结果。请问我的错是什么?

此处提供此错误的示例代码

<UNIT CODE START>
unit Unit21;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, TPLB3.Codec, TPLB3.BaseNonVisualComponent, TPLB3.CryptographicLibrary,
  Vcl.StdCtrls;

type
  TForm21 = class(TForm)
    Button1: TButton;
    CryptographicLibrary1: TCryptographicLibrary;
    Codec1: TCodec;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form21: TForm21;

implementation

{$R *.dfm}

procedure TForm21.Button1Click(Sender: TObject);
var s0,s1 : string;
begin
    codec1.Password := 'ou[asdl[kn';
    s0 := 'asdfghjkl';
    codec1.EncryptString(s0,s1);
    label1.caption := s1;
end;

end.
<UNIT CODE END>

<FORM CODE START>

object Form21: TForm21
  Left = 0
  Top = 0
  Caption = 'Form21'
  ClientHeight = 299
  ClientWidth = 635
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Label1: TLabel
    Left = 168
    Top = 72
    Width = 31
    Height = 13
    Caption = 'Label1'
  end
  object Button1: TButton
    Left = 32
    Top = 72
    Width = 75
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
    OnClick = Button1Click
  end
  object CryptographicLibrary1: TCryptographicLibrary
    Left = 192
    Top = 136
  end
  object Codec1: TCodec
    AsymetricKeySizeInBits = 512
    AdvancedOptions2 = []
    CryptoLibrary = CryptographicLibrary1
    Left = 200
    Top = 192
    StreamCipherId = 'native.StreamToBlock'
    BlockCipherId = 'native.AES-256'
    ChainId = 'native.CBC'
  end
end
<FORM CODE END>

1 个答案:

答案 0 :(得分:6)

乍一看问题似乎是你正在使用AES的 CBC (密码块链接)模式。

这实际上不是问题,但 CBC 模式的设计方式可以解决。

查看此维基百科文章,了解有关Block cipher mode of operation

的更多详情
  

在密码学中,操作模式是使用块的算法   密码提供信息服务,如机密性或   真实性。分组密码本身仅适用于安全   加密转换(加密或解密)的一个   固定长度的一组位称为块。一种操作方式   描述了如何重复应用密码的单块操作   安全地转换大于块的数据量。

     

...

     

在CBC模式下,每个明文块与前一个版本进行异或   加密前的密文块。这样,每个密文   block取决于到目前为止处理的所有明文块。至   使每个消息唯一,必须在中使用初始化向量   第一块。

如果您希望始终为某些纯文本接收相同的密文,则可以切换到基本的 ECB Electronic Codebook)模式(例如,更改ChainId = 'native.CBC'ChainId = 'native.ECB')。

但不建议这样做,因为它会使您的密文易受某​​些攻击。不应使用对称密码多次使用相同的密钥加密相同的纯文本。

这就是为什么引入了链接操作模式的原因。它们用于“生成”一系列派生密钥(基于您提供的密钥 - 在您的情况下基于密码),而不是基本密钥。

请务必阅读此问题:

  

如果您正在设计一个真实世界的系统(将由除您自己以外的其他人使用),并且您需要为其任何部分提供安全性,请花一些时间来了解有关加密的更多信息。

一个良好的开端是在密码学上采用类似的课程:Cryptography I(免费)

相关问题