[Java] Base64 encode & decode & isBase64
public static String encodeBase64(String s) {
return Base64.getEncoder().encodeToString(s.getBytes());
}
public static String decodeBase64(String s) {
try {
if (isBase64(s)) {
return new String(Base64.getDecoder().decode(s));
} else {
return s;
}
} catch (Exception e) {
return s;
}
}
public static boolean isBase64(String s) {
String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(s);
return m.find();
}
How to check whether a string is Base64 encoded or not
I want to decode a Base64 encoded string, then store it in my database. If the input is not Base64 encoded, I need to throw an error. How can I check if a string is Base64 encoded?
stackoverflow.com
https://www.baeldung.com/java-base64-encode-and-decode
https://dev-syhy.tistory.com/15
[Java] base64 인코딩 디코딩 (encoding / decoding)
일단 인코딩, 디코딩을 쉽게 설명을 하면 "hello world" 라는 단어를 인코딩을 하면 base64형태로 인코딩 됩니다. base64를 디코딩하면 "hello world"라고 나오게 되는 것이죠 자바 버전별로 사용되는게 너
dev-syhy.tistory.com
https://stackoverflow.com/questions/8571501/how-to-check-whether-a-string-is-base64-encoded-or-not
How to check whether a string is Base64 encoded or not
I want to decode a Base64 encoded string, then store it in my database. If the input is not Base64 encoded, I need to throw an error. How can I check if a string is Base64 encoded?
stackoverflow.com