【发布时间】:2018-03-07 08:03:40
【问题描述】:
我有问题。我想在 Delphi 程序中加密文本并在 java 中解密。我正在使用 AES/CBC/NoPadding 来做到这一点,但 java 程序不能很好地解密文本。 下一步是使用 PKCS5Padding,所以有人也可以回答这个问题,很高兴!
德尔福代码:
var
Cipher: TDCP_rijndael;
Key: string;
DataIn, DataOut: System.TArray<System.Byte>;
begin
Key := '0123456789012345';
DataIn := nil;
DataIn := TEncoding.UTF8.getbytes('SakisSakisSakisa');
DataOut := nil;
SetLength(DataOut, high(DataIn) + 1);
Cipher := TDCP_rijndael.create(nil);
Cipher.Algorithm := 'AES';
Cipher.Init(Key[1], 128, nil);
Cipher.EncryptCBC(DataIn[0], DataOut[0], high(DataIn) + 1);
Cipher.Free;
With TMemoryStream.create do begin
Write(DataOut[0], length(DataOut));
SaveToFile('c:\temp\encryption\sakisEnc.txt');
Free;
end;
DataIn 具有以下字节: 83,97,107,105,115,83,97,107,105,115,83,97,107,105,115,97 此代码生成具有以下字节的加密字节数组 DataOut: 3,207,105,252,118,38,28,145,89,77,107,8,181,205,190,165
现在是 Java 代码:
Path path = null;
String encryptionKey = null;
Cipher cipher = null;
SecretKeySpec key = null;
byte[] enc1;
path = FileSystems.getDefault().getPath("c:\\temp\\encryption\\SakisEnc.txt", "");
cipherText = Files.readAllBytes(path);
encryptionKey = "0123456789012345";
cipher = Cipher.getInstance("AES/CBC/NoPadding");
key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(encryptionKey.getBytes()));
dec1 = cipher.doFinal(cipherText);
dec1 字节数组应该具有与 Delphi DataIn 代码相同的字节 83,97,107,105,115,83,97,107,105,115,83,97,107,105,115,97 但它包含其他内容。
我真的无法理解我做错了什么..... 提前谢谢!
【问题讨论】:
-
不是问题,但是使用
Length(...)而不是high(...) +并使用TFileStream而不是TMemoryStream来写入文件。