1 /* 2 * Copyright (C) 2020 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 android.security; 18 19 import android.annotation.NonNull; 20 import android.hardware.security.keymint.HardwareAuthToken; 21 import android.hardware.security.secureclock.Timestamp; 22 23 import java.nio.ByteBuffer; 24 import java.nio.ByteOrder; 25 26 /** 27 * @hide This Utils class provides method(s) for AuthToken conversion. 28 */ 29 public class AuthTokenUtils { 30 AuthTokenUtils()31 private AuthTokenUtils(){ 32 } 33 34 /** 35 * Build a HardwareAuthToken from a byte array 36 * @param array byte array representing an auth token 37 * @return HardwareAuthToken representation of an auth token 38 */ toHardwareAuthToken(@onNull byte[] array)39 public static @NonNull HardwareAuthToken toHardwareAuthToken(@NonNull byte[] array) { 40 final HardwareAuthToken hardwareAuthToken = new HardwareAuthToken(); 41 42 // First byte is version, which does not exist in HardwareAuthToken anymore 43 // Next 8 bytes is the challenge. 44 hardwareAuthToken.challenge = 45 ByteBuffer.wrap(array, 1, 8).order(ByteOrder.nativeOrder()).getLong(); 46 47 // Next 8 bytes is the userId 48 hardwareAuthToken.userId = 49 ByteBuffer.wrap(array, 9, 8).order(ByteOrder.nativeOrder()).getLong(); 50 51 // Next 8 bytes is the authenticatorId. 52 hardwareAuthToken.authenticatorId = 53 ByteBuffer.wrap(array, 17, 8).order(ByteOrder.nativeOrder()).getLong(); 54 55 // while the other fields are in machine byte order, authenticatorType and timestamp 56 // are in network byte order. 57 // Next 4 bytes is the authenticatorType. 58 hardwareAuthToken.authenticatorType = 59 ByteBuffer.wrap(array, 25, 4).order(ByteOrder.BIG_ENDIAN).getInt(); 60 // Next 8 bytes is the timestamp. 61 final Timestamp timestamp = new Timestamp(); 62 timestamp.milliSeconds = 63 ByteBuffer.wrap(array, 29, 8).order(ByteOrder.BIG_ENDIAN).getLong(); 64 hardwareAuthToken.timestamp = timestamp; 65 66 // Last 32 bytes is the mac, 37:69 67 hardwareAuthToken.mac = new byte[32]; 68 System.arraycopy(array, 37 /* srcPos */, 69 hardwareAuthToken.mac, 70 0 /* destPos */, 71 32 /* length */); 72 73 return hardwareAuthToken; 74 } 75 } 76