blob: 52d1a90ed6b9f6cde00fedd3b5d8a9545e8d764b [file] [log] [blame]
margaretha56e8e552017-12-05 16:31:21 +01001package de.ids_mannheim.korap.authentication.http;
margaretha4b5c1412017-11-15 20:55:04 +01002
3import org.apache.commons.codec.binary.Base64;
4import org.springframework.stereotype.Component;
5
6import de.ids_mannheim.korap.exceptions.KustvaktException;
7import de.ids_mannheim.korap.utils.ParameterChecker;
8
9/** TransferEncoding contains encoding and decoding methods for data transfer,
10 * e.g. transfering credentials using basic Http authentication.
11 *
12 * @author margaretha
13 *
14 */
15@Component
16public class TransferEncoding {
17
18 /** Encodes username and password using Base64.
19 *
20 * @param username username
21 * @param password password
22 * @return
23 */
margaretha064eb6f2018-07-10 18:33:01 +020024 public static String encodeBase64 (String username, String password) {
margaretha4b5c1412017-11-15 20:55:04 +010025 String s = username + ":" + password;
26 return new String(Base64.encodeBase64(s.getBytes()));
27 }
28
29 /** Decodes the given string using Base64.
30 *
31 * @param encodedStr
32 * @return username and password as an array of strings.
33 * @throws KustvaktException
34 */
margaretha064eb6f2018-07-10 18:33:01 +020035 public static String[] decodeBase64 (String encodedStr)
margaretha4b5c1412017-11-15 20:55:04 +010036 throws KustvaktException {
37
38 ParameterChecker.checkStringValue(encodedStr, "encoded string");
39 String decodedStr = new String(Base64.decodeBase64(encodedStr));
40
41 if (decodedStr.contains(":") && decodedStr.split(":").length == 2) {
42 String[] strArr = decodedStr.split(":");
43 if ((strArr[0] != null && !strArr[0].isEmpty())
44 && (strArr[1] != null && !strArr[1].isEmpty())) {
45 return decodedStr.split(":");
46 }
47
48 }
49
50 throw new IllegalArgumentException(
51 "Unknown Base64 encoding format: " + decodedStr);
52 }
53}