RecoverySession.java revision 81ee34bf957dffe020442e3f0c6c06817397ebf0
1/*
2 * Copyright (C) 2018 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
17package android.security.keystore.recovery;
18
19import java.security.SecureRandom;
20
21/**
22 * Session to recover a {@link KeychainSnapshot} from the remote trusted hardware, initiated by a
23 * recovery agent.
24 *
25 * @hide
26 */
27public class RecoverySession implements AutoCloseable {
28
29    private static final int SESSION_ID_LENGTH_BYTES = 16;
30
31    private final String mSessionId;
32    private final RecoveryController mRecoveryController;
33
34    private RecoverySession(RecoveryController recoveryController, String sessionId) {
35        mRecoveryController = recoveryController;
36        mSessionId = sessionId;
37    }
38
39    /**
40     * A new session, started by {@code recoveryManager}.
41     */
42    static RecoverySession newInstance(RecoveryController recoveryController) {
43        return new RecoverySession(recoveryController, newSessionId());
44    }
45
46    /**
47     * Returns a new random session ID.
48     */
49    private static String newSessionId() {
50        SecureRandom secureRandom = new SecureRandom();
51        byte[] sessionId = new byte[SESSION_ID_LENGTH_BYTES];
52        secureRandom.nextBytes(sessionId);
53        StringBuilder sb = new StringBuilder();
54        for (byte b : sessionId) {
55            sb.append(Byte.toHexString(b, /*upperCase=*/ false));
56        }
57        return sb.toString();
58    }
59
60    /**
61     * An internal session ID, used by the framework to match recovery claims to snapshot responses.
62     */
63    String getSessionId() {
64        return mSessionId;
65    }
66
67    @Override
68    public void close() {
69        mRecoveryController.closeSession(this);
70    }
71}
72