8208583: Better management of internal KeyStore buffers

Reviewed-by: weijun
This commit is contained in:
Sean Coffey 2018-08-03 14:14:59 +01:00
parent 4555c28590
commit 7a791910c3
6 changed files with 105 additions and 67 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -29,6 +29,7 @@ import java.lang.ref.Reference;
import java.security.MessageDigest;
import java.security.KeyRep;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Locale;
import javax.crypto.SecretKey;
import javax.crypto.spec.PBEKeySpec;
@ -54,7 +55,8 @@ final class PBEKey implements SecretKey {
*
* @param keytype the given PBE key specification
*/
PBEKey(PBEKeySpec keySpec, String keytype) throws InvalidKeySpecException {
PBEKey(PBEKeySpec keySpec, String keytype, boolean useCleaner)
throws InvalidKeySpecException {
char[] passwd = keySpec.getPassword();
if (passwd == null) {
// Should allow an empty password.
@ -71,13 +73,15 @@ final class PBEKey implements SecretKey {
this.key = new byte[passwd.length];
for (int i=0; i<passwd.length; i++)
this.key[i] = (byte) (passwd[i] & 0x7f);
java.util.Arrays.fill(passwd, ' ');
Arrays.fill(passwd, ' ');
type = keytype;
// Use the cleaner to zero the key when no longer referenced
final byte[] k = this.key;
CleanerFactory.cleaner().register(this,
() -> java.util.Arrays.fill(k, (byte)0x00));
if (useCleaner) {
final byte[] k = this.key;
CleanerFactory.cleaner().register(this,
() -> Arrays.fill(k, (byte) 0x00));
}
}
public byte[] getEncoded() {
@ -122,10 +126,22 @@ final class PBEKey implements SecretKey {
byte[] thatEncoded = that.getEncoded();
boolean ret = MessageDigest.isEqual(this.key, thatEncoded);
java.util.Arrays.fill(thatEncoded, (byte)0x00);
Arrays.fill(thatEncoded, (byte)0x00);
return ret;
}
/**
* Clears the internal copy of the key.
*
*/
@Override
public void destroy() {
if (key != null) {
Arrays.fill(key, (byte) 0x00);
key = null;
}
}
/**
* readObject is called to restore the state of this key from
* a stream.