Base64 和 MimeUtility 之间的不同结果

Different results between Base64 and MimeUtility

我正在尝试将使用 Base64OutputStream 与 MimeUtility 和 运行 的方法更新为略有不同的结果。

原始方法如下所示:

private static String encodePassword(String password) {
    MessageDigest algorithm;
    try {
        algorithm = MessageDigest.getInstance("MD5");
        algorithm.reset();
        algorithm.update(password.getBytes());
        byte[] encrypted =  algorithm.digest();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OutputStream encoder = MimeUtility.encode(out, "base64");

        encoder.write(encrypted);
        encoder.flush();
        return new String(out.toByteArray());
    } catch (NoSuchAlgorithmException e) {
        return "Bad Encryption";
    } catch (MessagingException e) {
        return "Bad Encryption";
    } catch (IOException e) {
        return "Bad Encryption";
    }

这是我更新的方法:

private static String encodePassword(String password) {
    MessageDigest algorithm;
    try {
        algorithm = MessageDigest.getInstance("MD5");
        algorithm.reset();
        algorithm.update(password.getBytes());
        byte[] encrypted =  algorithm.digest();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OutputStream encoder = new Base64OutputStream(out);

        encoder.write(encrypted);
        encoder.flush();
        return new String(out.toByteArray());

    } catch (NoSuchAlgorithmException e) {
        return "Bad Encryption";
    } catch (IOException e) {
        return "Bad Encryption";
    }
}

第一种方法returns正确的加密方式:"ISMvKXpXpadDiUoOSoAfww==" 第二个 returns 大部分 - "ISMvKXpXpadDiUoOSoAf"

我做错了什么?

假设您正在使用 https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64OutputStream.html

如文档所述:

Note: It is mandatory to close the stream after the last byte has been written to it, otherwise the final padding will be omitted and the resulting data will be incomplete/inconsistent.

您需要在完成写入后关闭流。

缺少的 == 是末尾的填充,因为 base 64 在 3 个字符块中工作。当你的长度不能被 3 整除时,你用一两个 = 个字符

填充结果