加密 Jar 文件,更改数据,再次加密并保存


Encrypt Jar file, alterate data, encrypt it again and save

我需要制作一个php脚本来执行以下顺序:

  • 1)用户输入一个密钥,我们称之为$user_key
  • 2)读取默认文件内容(file_get_contents保存在$data)
  • 3
  • )使用3个随机密钥加密AES 128中的$data(保存在$data)
  • 4)在$data末尾连接这3个键
  • 5) 填充数据
  • 6) 使用用户的密钥加密$data
  • 7) 将$data写入唯一文件

如果我只做第 1、2、4、5、6 和 7 部分,它可以工作(Java 解密)。如果我使用随机密钥加密文件,它根本不起作用(Java 解密不起作用)。

我在 php 中做错了什么(比如缺少填充或其他东西)?

这是我使用的代码。我已经标记了第 1 行到 3 行,这些行为使脚本无法正常工作。

$data = file_get_contents('default_file.jar');
// Generate 3 AES keys
$ramdom_key_1 = randomAESKey();
$ramdom_key_2 = randomAESKey();
$ramdom_key_3 = randomAESKey();
// Encrypt three times the raw data with the user key
$data = AESEncrypt(pad($data, 16), $ramdom_key_1);      // LINE 1
$data = AESEncrypt($data, $ramdom_key_2);               // LINE 2
$data = AESEncrypt($data, $ramdom_key_3);               // LINE 3
// Add the 3 keys to the data raw
$data .= $ramdom_key_3 . $ramdom_key_2 . $ramdom_key_1;
// Final encryption with the user's key
$data = AESEncrypt(pad($data, 16), $user_key);
// Write the raw data to an unique file
file_put_contents('new_file.jar', $data);

这是我解密文件的 Java 代码:

byte[] content = download(url);
content = Crypto.decrypt(content, user_key);
String content = new String(data);
String keys = content.substring(content.length() - 48, content.length());
String[] keys = new String[] { keys.substring(0, 16), keys.substring(16, 32), keys.substring(32, 48) };
byte[] cleared_content = new byte[content.length - 48];
System.arraycopy(content, 0, cleared_content, 0, content.length - 48);
// For each keys, decrypt the file data
for (String key : keys)
{
    cleared_content = Crypto.decrypt(cleared_content, key.getBytes());
}
return cleared_content;

我的加密类看起来像这样(只是其中的一小部分):

public static byte[] decrypt(byte[] input)
{
    try
    {
        SecretKeySpec skey = new SecretKeySpec(KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skey);
        return cipher.doFinal(input);
    }
    catch (Exception e) {}
    return input;
}

由于密钥以 desc 顺序存储,我只需要像这样执行解密即可。

快速编辑以在 php 中显示我的 pad 函数:

function pad($data, $blocksize)
{ 
    $pad = $blocksize - (strlen($data) % $blocksize); 
    return $data . str_repeat(chr($pad), $pad); 
}

问题解决了。感谢猫头鹰。

我变了

$data = AESEncrypt(pad($data, 16), $ramdom_key_1);      // LINE 1
$data = AESEncrypt($data, $ramdom_key_2);               // LINE 2
$data = AESEncrypt($data, $ramdom_key_3);               // LINE 3

$data = AESEncrypt(pad($data, 16), $ramdom_key_1);      // LINE 1
$data = AESEncrypt(pad($data, 16), $ramdom_key_2);      // LINE 2
$data = AESEncrypt(pad($data, 16), $ramdom_key_3);      // LINE 3