Base64: java.lang.IllegalArgumentException: Illegal character

2022-09-01 01:04:40

我正在尝试在用户注册后发送确认电子邮件。为此,我使用JavaMail库和Java 8 Base64 util类。

我通过以下方式对用户电子邮件进行编码:

byte[] encodedEmail = Base64.getUrlEncoder().encode(user.getEmail().getBytes(StandardCharsets.UTF_8));
Multipart multipart = new MimeMultipart();
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-type", "text/html; charset=UTF-8");
String confirmLink = "Complete your registration by clicking on following"+ "\n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
MimeBodyPart link = new MimeBodyPart(headers,
confirmLink.getBytes("UTF-8"));
multipart.addBodyPart(link);

在哪里:confirmationURL

private final static String confirmationURL = "http://localhost:8080/project/controller?command=confirmRegistration&ID=";

然后在 ConfirmRegistrationCommand 中以如下方式对其进行解码:

    String encryptedEmail = request.getParameter("ID");

    String decodedEmail = new String(Base64.getUrlDecoder().decode(encryptedEmail), StandardCharsets.UTF_8);

    RepositoryFactory repositoryFactory = RepositoryFactory
            .getFactoryByName(FactoryType.MYSQL_REPOSITORY_FACTORY);
    UserRepository userRepository = repositoryFactory.getUserRepository();
    User user = userRepository.find(decodedEmail);

    if (user.getEmail().equals(decodedEmail)) {
        user.setActiveStatus(true);
        return Path.WELCOME_PAGE;
    } else {
        return Path.ERROR_PAGE;
    }

当我尝试解码时:

http://localhost:8080/project/controller?command=confirmRegistration&ID=[B@6499375d

我得到.java.lang.IllegalArgumentException: Illegal base64 character 5b

我试图使用基本的编码/解码器(不是URL),但没有成功。

解决:

问题是下一个 - 在行中:

 String confirmLink = "Complete your registration by clicking on following"+ "\n<a href='" + confirmationURL + encodedEmail + "'>link</a>";

我正在对字节数组调用string,所以我应该执行以下操作:

String encodedEmail = new String(Base64.getEncoder().encode(
                user.getEmail().getBytes(StandardCharsets.UTF_8)));

感谢Jon SkeetByteHamster


答案 1

您的编码文本是 。这不是Base64,编码时出了点问题。该解码代码看起来不错。[B@6499375d

在将 byte[] 添加到 URL 之前,请使用以下代码将 byte[] 转换为字符串:

String encodedEmailString = new String(encodedEmail, "UTF-8");
// ...
String confirmLink = "Complete your registration by clicking on following"
    + "\n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";

答案 2

我遇到了这个错误,因为我的编码图像以.data:image/png;base64,iVBORw0...

这个答案让我找到了解决方案:

String partSeparator = ",";
if (data.contains(partSeparator)) {
  String encodedImg = data.split(partSeparator)[1];
  byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
  Path destinationFile = Paths.get("/path/to/imageDir", "myImage.png");
  Files.write(destinationFile, decodedImg);
}

该代码删除 Base64 编码图像前面的元数据,并将 Base64 字符串传递给 Java 的 Base64.Decoder,以字节的形式获取图像。


推荐