Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2016 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 package com.android.apksig.internal.util;
     17 
     18 import com.android.apksig.util.DataSink;
     19 import java.nio.ByteBuffer;
     20 import java.security.MessageDigest;
     21 
     22 /**
     23  * Data sink which feeds all received data into the associated {@link MessageDigest} instances. Each
     24  * {@code MessageDigest} instance receives the same data.
     25  */
     26 public class MessageDigestSink implements DataSink {
     27 
     28     private final MessageDigest[] mMessageDigests;
     29 
     30     public MessageDigestSink(MessageDigest[] digests) {
     31         mMessageDigests = digests;
     32     }
     33 
     34     @Override
     35     public void consume(byte[] buf, int offset, int length) {
     36         for (MessageDigest md : mMessageDigests) {
     37             md.update(buf, offset, length);
     38         }
     39     }
     40 
     41     @Override
     42     public void consume(ByteBuffer buf) {
     43         int originalPosition = buf.position();
     44         for (MessageDigest md : mMessageDigests) {
     45             // Reset the position back to the original because the previous iteration's
     46             // MessageDigest.update set the buffer's position to the buffer's limit.
     47             buf.position(originalPosition);
     48             md.update(buf);
     49         }
     50     }
     51 }
     52