| margaretha | 56e8e55 | 2017-12-05 16:31:21 +0100 | [diff] [blame] | 1 | package de.ids_mannheim.korap.authentication.http; |
| margaretha | 4b5c141 | 2017-11-15 20:55:04 +0100 | [diff] [blame] | 2 | |
| 3 | import org.apache.commons.codec.binary.Base64; |
| 4 | import org.springframework.stereotype.Component; |
| 5 | |
| 6 | import de.ids_mannheim.korap.exceptions.KustvaktException; |
| 7 | import 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 |
| 16 | public class TransferEncoding { |
| 17 | |
| 18 | /** Encodes username and password using Base64. |
| 19 | * |
| 20 | * @param username username |
| 21 | * @param password password |
| 22 | * @return |
| 23 | */ |
| margaretha | 064eb6f | 2018-07-10 18:33:01 +0200 | [diff] [blame] | 24 | public static String encodeBase64 (String username, String password) { |
| margaretha | 4b5c141 | 2017-11-15 20:55:04 +0100 | [diff] [blame] | 25 | 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 | */ |
| margaretha | 064eb6f | 2018-07-10 18:33:01 +0200 | [diff] [blame] | 35 | public static String[] decodeBase64 (String encodedStr) |
| margaretha | 4b5c141 | 2017-11-15 20:55:04 +0100 | [diff] [blame] | 36 | 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 | } |