Fixed
Status Update
Comments
ap...@google.com <ap...@google.com> #2
Hi Ed, Thank you so much for these suggestions. I've been reviewing them and merging them in. Hopefully it should be live. I've included a thank you note too in the article.
da...@google.com <da...@google.com>
na...@google.com <na...@google.com> #3
Great! Thanks a lot, I'll look for the live updates soon!
Description
```
public void basicTest() throws Exception {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
throw new RuntimeException("API v23 or higher is required to run this test");
}
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(/* param= */ null);
final ArrayList<Exception> exceptions = new ArrayList<>();
Thread thread =
new Thread() {
@Override
public void run() {
try {
MasterKey masterKey =
new MasterKey.Builder(ApplicationProvider.getApplicationContext())
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();
} catch (Exception e) {
synchronized (exceptions) {
exceptions.add(e);
}
}
}
};
// This starts a new thread that generates a new master key. I think that thread blocks until
// the new master key is finished.
thread.start();
// We now try to create another master key in this thread.
MasterKey masterKey =
new MasterKey.Builder(ApplicationProvider.getApplicationContext())
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();
// This should be true, but it is sometimes false.
assertThat(keyStore.containsAlias("_androidx_security_master_key_")).isTrue();
// Wait for other thread to finish
thread.join();
if (exceptions.size() > 0) {
throw exceptions.get(0);
}
}
```
This is because of a non-atomic check and set in `MasterKeys.getOrCreate`.
Reported by juerg@google.com