0

Communicate with encrypted parameters between Java and Delphi. If Delphi encrypts them, Java needs to decrypt them. But if I operate as below, Java will have an error... How should I change the Java sauce?

[ Delphi source (Encrypt) ]

var
  Data: string;
begin
  Data := Memo1.Text;
  DCP_rijndael1.InitStr(Edt_Password.Text, TDCP_sha256);
  DCP_rijndael1.EncryptCBC(Data[1],Data[1],Length(Data));
  DCP_rijndael1.Burn;
  Memo2.Text := Base64EncodeStr(Data);
end;

[ Delphi source (Decrypt) ]

var
  Data: string;
begin
  Data := Base64DecodeStr(Memo2.Text);
  DCP_rijndael1.InitStr(Edt_Password.Text, TDCP_sha256);
  DCP_rijndael1.DecryptCBC(Data[1],Data[1],Length(Data));
  DCP_rijndael1.Burn;
  Memo3.Text := Data;
end;

[Java source]

public static String Decrypt(String text, String key) throws Exception

{

          Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

          byte[] keyBytes= new byte[16];

          byte[] b= key.getBytes("UTF-8");

          int len= b.length;

          if (len > keyBytes.length) len = keyBytes.length;

          System.arraycopy(b, 0, keyBytes, 0, len);

          SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

          IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);

          cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);


          sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();

          byte [] results = cipher.doFinal(decoder.decodeBuffer(text));

          return new String(results,"UTF-8");

}
강혜리
  • 11
  • 2

1 Answers1

0

The Delphi code defines that the password should be hashed using SHA-256. (TDCP_sha256). I don't know how the DCP encryption is implemented but I would assume that the SHA256 hash of the password is used as AES key, hence AES256 is used here.

The Java code however does not make any use of SHA-256 to hash the key as it is called here.

Furthermore on Delphi side you use CBC mode but you don't specify the IV via SetIV method. On Java side you specify the IV using the key which is heavily insecure). The IV has to be initialized by secure random data. Never use something different!

The common way is to generate a random IV before encryption and then prepend it the encrypted data and read it back before the decryption takes place.

Robert
  • 39,162
  • 17
  • 99
  • 152
  • 1
    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "SHA-256"); – 강혜리 Jun 26 '20 at 13:03
  • This is an error. Which part do I need to correct? Can you give me an example? – 강혜리 Jun 26 '20 at 13:04
  • 1
    There is no "auto-hashing" in Java. Create a MessageDigest for SHA256, hash the password and use the result in SecretKeySpec. https://stackoverflow.com/a/5531479/150978 – Robert Jun 26 '20 at 13:08