1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settings.connecteddevice.audiosharing;
18 
19 import com.android.settings.widget.ValidatedEditTextPreference;
20 
21 import java.nio.charset.StandardCharsets;
22 
23 /**
24  * Validator for Audio Sharing Password, which should be a UTF-8 string that has at least 4 octets
25  * and should not exceed 16 octets.
26  */
27 public class AudioSharingPasswordValidator implements ValidatedEditTextPreference.Validator {
28     private static final int MIN_OCTETS = 4;
29     private static final int MAX_OCTETS = 16;
30 
31     @Override
isTextValid(String value)32     public boolean isTextValid(String value) {
33         if (value == null
34                 || getOctetsCount(value) < MIN_OCTETS
35                 || getOctetsCount(value) > MAX_OCTETS) {
36             return false;
37         }
38 
39         return isValidUTF8(value);
40     }
41 
getOctetsCount(String value)42     private static int getOctetsCount(String value) {
43         return value.getBytes(StandardCharsets.UTF_8).length;
44     }
45 
isValidUTF8(String value)46     private static boolean isValidUTF8(String value) {
47         byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
48         String reconstructedString = new String(bytes, StandardCharsets.UTF_8);
49         return value.equals(reconstructedString);
50     }
51 }
52