Base64编码:java.lang.IllegalArgumentException异常:非法字符

问题描述 投票:17回答:5

我想用户注册后发送一封确认邮件。我使用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>";

我的字节数组上调用toString,所以我应该做到以下几点:

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

由于乔恩斯基特和ByteHamster。

java base64 javamail registration
5个回答
19
投票

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

使用此代码,将其添加到网址前的字节[]转换成字符串:

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

11
投票

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

This answer导致我的解决方案:

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.jpg");
  Files.write(destinationFile, decodedImg);
}

2
投票

只需使用下面的代码来解决此问题:

JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1].
                        replace('-', '+').replace('_', '/')))).readObject();

在上面的代码replace('-', '+').replace('_', '/')做的工作。欲了解更多详细信息,请参阅https://jwt.io/js/jwt.js。我的理解从代码的一部分的问题,从该链接了:

function url_base64_decode(str) {
  var output = str.replace(/-/g, '+').replace(/_/g, '/');
  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += '==';
      break;
    case 3:
      output += '=';
      break;
    default:
      throw 'Illegal base64url string!';
  }
  var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
  try{
    return decodeURIComponent(escape(result));
  } catch (err) {
    return result;
  }
}

1
投票

该Base64.Encoder.encodeToString方法自动使用ISO-8859-1字符集。

对于加密工具我写,我把密文的输入字符串和Base64编码它的传输,然后逆转的过程。下面示出相关部分。注:我的file.encoding属性在JVM的调用设置为ISO-8859-1,这样也可以有一个轴承。

static String getBase64EncodedCipherText(String cipherText) {
    byte[] cText = cipherText.getBytes();
    // return an ISO-8859-1 encoded String
    return Base64.getEncoder().encodeToString(cText);
}

static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
    return new String((Base64.getDecoder().decode(encodedCipherText)));
}

public static void main(String[] args) {
    try {
        String cText = getRawCipherText(null, "Hello World of Encryption...");

        System.out.println("Text to encrypt/encode: Hello World of Encryption...");
        // This output is a simple sanity check to display that the text
        // has indeed been converted to a cipher text which 
        // is unreadable by all but the most intelligent of programmers.
        // It is absolutely inhuman of me to do such a thing, but I am a
        // rebel and cannot be trusted in any way.  Please look away.
        System.out.println("RAW CIPHER TEXT: " + cText);
        cText = getBase64EncodedCipherText(cText);
        System.out.println("BASE64 ENCODED: " + cText);
        // There he goes again!!
        System.out.println("BASE64 DECODED:  " + getBase64DecodedCipherText(cText));
        System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

输出看起来像:

Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;�C�l��<8��U���X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED:  q$;�C�l��<8��U���X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...

0
投票

我得到这个错误我的Linux詹金斯奴隶。我固定它由从节点改变了“已知的主机文件验证战略”到“非验证验证策略”。

© www.soinside.com 2019 - 2024. All rights reserved.