이번에 백엔드 개발중에 '&' 포함된 특수문자가 들어가면서 url에서 파라미터가 검색이 안되는 현상이 발생했다.
이후 base 64로 인코딩을 하여 디코딩해서 사용했는데 어떠한 특수한 경우에 이와 같은 오류가 발생했다.
오류:
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
이전 :
function base64(str) {
return btoa(str);
}
변경을 해줬다
function utf8ToBase64(str) {
return btoa(unescape(encodeURIComponent(str)));
}
const originalString = "all"; // 포함된 UTF-8 문자열
const encodedString = utf8ToBase64(originalString);
console.log(encodedString); //
문제는 여기서 또 발생하였다.
오류:
illegal base64 character 20; nested exception is java.lang.illegalargumentexception: illegal base64 character 20
이부분에 이상했던점이 한글을 인코딩하는데,
front 부분에서 특수문자인 '+'가 들어가게 되었고, url에선 '+'를 공백처리해버려서 디코딩이 잘되지 않았습니다.
그래서 이를 해결하기 위해
Hex 인코딩을 하게되었습니다.
해결:
프론트 :
function utf8ToHex(str) {
const utf8Bytes = new TextEncoder().encode(str);
return Array.from(utf8Bytes).map(byte => byte.toString(16).padStart(2, '0')).join('');
}
const originalString = "안녕하세요";
const encodedHex = utf8ToHex(originalString);
console.log(encodedHex);
백엔드:
public String hexDecode(String encodedHex){
byte[] decodedBytes = new byte[encodedHex.length() / 2];
for (int i = 0; i < encodedHex.length(); i += 2) {
decodedBytes[i / 2] = (byte) ((Character.digit(encodedHex.charAt(i), 16) << 4)
+ Character.digit(encodedHex.charAt(i + 1), 16));
}
String decodedString = new String(decodedBytes, StandardCharsets.UTF_8);
return decodedString;
}