簡體   English   中英

用Java解密/解密“AES / ECB / PKCS5Padding”

[英]En-/decrypt “AES/ECB/PKCS5Padding” in Java

誰能告訴我如何解密用這個PHP函數加密的數據(使用Java)?

PHP代碼

    public function pad($data, $blocksize = 16) {
        $pad = $blocksize - (strlen($data) % $blocksize);
        return $data . str_repeat(chr($pad), $pad);
    }
    public function decryptECB($data) {
        return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::BLOB_ENCRYPTION_KEY, self::pad($data), MCRYPT_MODE_ECB);
    }
    public function encryptECB($data) {
        return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::BLOB_ENCRYPTION_KEY, self::pad($data), MCRYPT_MODE_ECB);
    }

我在這里嘗試了大部分的東西,但大多數都沒有填充,即使我添加填充它們也不起作用。

編輯1:

(來自PHP)

輸入看起來像這樣: http//pastebin.com/2cyig9nh

關鍵是:

M02cnQ51Ji97vwT4

輸出是這樣的: http//pastebin.com/XcA50UGH

(Java代碼)

public class Mcrypt {

private SecretKeySpec keyspec;
private Cipher cipher;

private String SecretKey = "M02cnQ51Ji97vwT4";

public Mcrypt() {
    keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
    try {
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    }
}

public String encrypt(String text) throws Exception {
    if (text == null || text.length() == 0)
        throw new Exception("Empty string");
    byte[] encrypted = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, keyspec );
            encrypted = cipher.doFinal(padString(text).getBytes());
        } catch (Exception e) {
            throw new Exception("[encrypt] " + e.getMessage());
        }
    return Base64.encodeBase64String(encrypted);
}

public byte[] decrypt(String code) throws Exception {
    if (code == null || code.length() == 0)
        throw new Exception("Empty string");
    byte[] decrypted = null;

    try {
        cipher.init(Cipher.DECRYPT_MODE, keyspec );
        decrypted = cipher.doFinal(new Base64().decode(code.getBytes()));
    } catch (Exception e) {
        throw new Exception("[decrypt] " + e.getMessage());
    }
    return decrypted;
}

private static String padString(String source) {
    char paddingChar = ' ';
    int size = 16;
    int x = source.length() % size;
    int padLength = size - x;
    for (int i = 0; i < padLength; i++) {
        source += paddingChar;
    }
    return source;
}
}

您正在Java代碼中對Base64進行編碼和解碼,但您的PHP代碼似乎無法執行任何編碼/解碼。 這似乎可以通過您在Pastebin上發布的內容得到證實。 如果你想使用字符串而不是字節 - 字節是現代密碼接受的唯一輸入 - 那么你應該確保雙方的(字符)編碼是正確的。 如果您只想使用字節,請不要在Java中解碼二進制文件 - 輸入已經是字節,而不是文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM