2 * Copyright 2011 Google Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.ipc.invalidation.ticl;
19 import com.google.ipc.invalidation.common.DigestFunction;
20 import com.google.ipc.invalidation.external.client.SystemResources.Logger;
21 import com.google.ipc.invalidation.ticl.proto.Client.PersistentStateBlob;
22 import com.google.ipc.invalidation.ticl.proto.Client.PersistentTiclState;
23 import com.google.ipc.invalidation.util.Bytes;
24 import com.google.ipc.invalidation.util.ProtoWrapper.ValidationException;
25 import com.google.ipc.invalidation.util.TypedUtil;
28 * Utility methods for handling the Ticl persistent state.
31 public class PersistenceUtils {
33 /** Serializes a Ticl state blob. */
34 public static byte[] serializeState(
35 PersistentTiclState state, DigestFunction digestFn) {
36 Bytes mac = generateMac(state, digestFn);
37 return PersistentStateBlob.create(state, mac).toByteArray();
41 * Deserializes a Ticl state blob. Returns either the parsed state or {@code null}
42 * if it could not be parsed.
44 public static PersistentTiclState deserializeState(Logger logger, byte[] stateBlobBytes,
45 DigestFunction digestFn) {
46 PersistentStateBlob stateBlob;
48 // Try parsing the envelope protocol buffer.
49 stateBlob = PersistentStateBlob.parseFrom(stateBlobBytes);
50 } catch (ValidationException exception) {
51 logger.severe("Failed deserializing Ticl state: %s", exception.getMessage());
55 // Check the mac in the envelope against the recomputed mac from the state.
56 PersistentTiclState ticlState = stateBlob.getTiclState();
57 Bytes mac = generateMac(ticlState, digestFn);
58 if (!TypedUtil.<Bytes>equals(mac, stateBlob.getAuthenticationCode())) {
59 logger.warning("Ticl state failed MAC check: computed %s vs %s", mac,
60 stateBlob.getAuthenticationCode());
66 /** Returns a message authentication code over {@code state}. */
67 private static Bytes generateMac(PersistentTiclState state, DigestFunction digestFn) {
69 digestFn.update(state.toByteArray());
70 return new Bytes(digestFn.getDigest());
73 private PersistenceUtils() {
74 // Prevent instantiation.