繁体   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