1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 package android.util.apk;
18 
19 import android.annotation.Nullable;
20 
21 import java.security.cert.CertificateEncodingException;
22 import java.security.cert.X509Certificate;
23 import java.util.Arrays;
24 
25 /**
26  * For legacy reasons we need to return exactly the original encoded certificate bytes, instead
27  * of letting the underlying implementation have a shot at re-encoding the data.
28  */
29 class VerbatimX509Certificate extends WrappedX509Certificate {
30     private final byte[] mEncodedVerbatim;
31     private int mHash = -1;
32 
VerbatimX509Certificate(X509Certificate wrapped, byte[] encodedVerbatim)33     VerbatimX509Certificate(X509Certificate wrapped, byte[] encodedVerbatim) {
34         super(wrapped);
35         this.mEncodedVerbatim = encodedVerbatim;
36     }
37 
38     @Override
getEncoded()39     public byte[] getEncoded() throws CertificateEncodingException {
40         return mEncodedVerbatim;
41     }
42 
43     @Override
equals(@ullable Object o)44     public boolean equals(@Nullable Object o) {
45         if (this == o) return true;
46         if (!(o instanceof VerbatimX509Certificate)) return false;
47 
48         try {
49             byte[] a = this.getEncoded();
50             byte[] b = ((VerbatimX509Certificate) o).getEncoded();
51             return Arrays.equals(a, b);
52         } catch (CertificateEncodingException e) {
53             return false;
54         }
55     }
56 
57     @Override
hashCode()58     public int hashCode() {
59         if (mHash == -1) {
60             try {
61                 mHash = Arrays.hashCode(this.getEncoded());
62             } catch (CertificateEncodingException e) {
63                 mHash = 0;
64             }
65         }
66         return mHash;
67     }
68 }
69