ExtensionRegistry protoRegistry = registry.getProtoExtensions();
// Retain the core
if (!data.hasCore()) {
// Core field is required
throw new InvalidKeyDataException(
InvalidKeyDataException.Reason.PROTO_PARSE, null);
}
coreBytes = data.getCore();
// Parse the core, containing the security/usage constraints
KeyCore core;
try {
core = KeyCore.parseFrom(coreBytes, protoRegistry);
} catch (InvalidProtocolBufferException ex) {
throw new InvalidKeyDataException(
InvalidKeyDataException.Reason.PROTO_PARSE, ex);
}
// TODO(darylseah): extract security properties from core
// Extract the key version list
final int kvCount = data.getKeyVersionCount();
keyVersions.ensureCapacity(kvCount);
UnregisteredKeyVersionException unregisteredException = null;
InvalidKeyDataException buildException = null;
for (KeyVersionData kvData : data.getKeyVersionList()) {
if (!kvData.hasType()) {
// Type field is required
throw new InvalidKeyDataException(
InvalidKeyDataException.Reason.PROTO_PARSE, null);
}
try {
KeyVersion kv = registry.newBuilder(kvData.getType())
.withData(kvData, protoRegistry).build();
keyVersions.add(kv);
} catch (InvalidProtocolBufferException ex) {
// Throw proto parsing exceptions immediately
throw new InvalidKeyDataException(
InvalidKeyDataException.Reason.PROTO_PARSE, ex);
} catch (RuntimeException ex) {
// We consider runtime exceptions to be parsing exceptions
throw new InvalidKeyDataException(
InvalidKeyDataException.Reason.PROTO_PARSE, ex);
} catch (BuilderException ex) {
// Delay-throw builder exceptions...
buildException = new InvalidKeyDataException(
InvalidKeyDataException.Reason.KEY_VERSION_BUILD, ex);
} catch (UnregisteredKeyVersionException ex) {
// ...and unregistered key version exceptions
unregisteredException = ex;
}
}
// Unregistered key versions take precedence over build exceptions
if (unregisteredException != null) {
throw unregisteredException;
} else if (buildException != null) {
throw buildException;
}
// Extract the primary
if (kvCount > 0) {
int primaryIndex = (data.hasPrimary() ? data.getPrimary() : -1);
if (primaryIndex < 0 || primaryIndex >= keyVersions.size()) {
throw new InvalidKeyDataException(
InvalidKeyDataException.Reason.CORRUPTED_PRIMARY, null);
}
primary = keyVersions.get(primaryIndex);
}
}