• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ////////////////////////////////////////////////////////////////////////////////
16 
17 package com.google.crypto.tink.util;
18 
19 import com.google.crypto.tink.SecretKeyAccess;
20 import com.google.crypto.tink.subtle.Random;
21 import com.google.errorprone.annotations.Immutable;
22 import java.security.MessageDigest;
23 
24 /** A class storing an immutable byte array, protecting the data via {@link SecretKeyAccess}. */
25 @Immutable
26 public final class SecretBytes {
27   private final Bytes bytes;
28 
SecretBytes(Bytes bytes)29   private SecretBytes(Bytes bytes) {
30     this.bytes = bytes;
31   }
32 
33   /**
34    * Creates a new SecretBytes with the contents given in {@code value}.
35    *
36    * <p>The parameter {@code access} must be non-null.
37    */
copyFrom(byte[] value, SecretKeyAccess access)38   public static SecretBytes copyFrom(byte[] value, SecretKeyAccess access) {
39     if (access == null) {
40       throw new NullPointerException("SecretKeyAccess required");
41     }
42     return new SecretBytes(Bytes.copyFrom(value));
43   }
44 
45   /** Creates a new SecretBytes with bytes chosen uniformly at random of length {@code length}. */
randomBytes(int length)46   public static SecretBytes randomBytes(int length) {
47     return new SecretBytes(Bytes.copyFrom(Random.randBytes(length)));
48   }
49 
50   /**
51    * Returns a copy of the bytes wrapped by this object.
52    *
53    * <p>The parameter {@code access} must be non-null.
54    */
toByteArray(SecretKeyAccess access)55   public byte[] toByteArray(SecretKeyAccess access) {
56     if (access == null) {
57       throw new NullPointerException("SecretKeyAccess required");
58     }
59     return bytes.toByteArray();
60   }
61 
62   /** Returns the length of the bytes wrapped by this object. */
size()63   public int size() {
64     return bytes.size();
65   }
66 
67   /**
68    * Returns true if the {@code other} byte array has the same bytes, in time depending only on the
69    * length of both SecretBytes objects.
70    */
equalsSecretBytes(SecretBytes other)71   public boolean equalsSecretBytes(SecretBytes other) {
72     byte[] myArray = bytes.toByteArray();
73     byte[] otherArray = other.bytes.toByteArray();
74     return MessageDigest.isEqual(myArray, otherArray);
75   }
76 }
77