Search in sources :

Example 16 with DigestException

use of java.security.DigestException in project hbase by apache.

the class Encryption method hash256.

/**
   * Return the SHA-256 digest of the concatenation of the supplied arguments.
   */
public static byte[] hash256(String... args) {
    byte[] result = new byte[32];
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        for (String arg : args) {
            md.update(Bytes.toBytes(arg));
        }
        md.digest(result, 0, result.length);
        return result;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (DigestException e) {
        throw new RuntimeException(e);
    }
}
Also used : DigestException(java.security.DigestException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 17 with DigestException

use of java.security.DigestException in project j2objc by google.

the class MessageDigest1Test method testSHAProvider.

/**
     * Tests SHA MessageDigest provider
     */
public void testSHAProvider() {
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
        fail("unexpected exception: " + e);
    }
    byte[] bytes = new byte[] { 1, 1, 1, 1, 1 };
    // testing combination with provider
    try {
        // offset < 0
        md.update(bytes, -1, 1);
        fail("No expected IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        md.update(bytes, 1, -1);
        fail("No expected IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
    //Regression for Harmony-1148
    try {
        md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
        fail("unexpected exception: " + e);
    }
    try {
        // offset < 0
        md.digest(bytes, 0, -1);
        fail("No expected DigestException");
    } catch (DigestException e) {
    }
    try {
        // len < 0
        md.digest(bytes, -1, 0);
        fail("No expected DigestException");
    } catch (DigestException e) {
    }
    try {
        md = MessageDigest.getInstance("UnknownDigest");
        fail("expected NoSuchAlgorithmException");
    } catch (NoSuchAlgorithmException e) {
    // ok
    }
}
Also used : DigestException(java.security.DigestException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 18 with DigestException

use of java.security.DigestException in project j2objc by google.

the class MessageDigest1Test method test_digestLB$LILI.

/**
     * java.security.MessageDigest#digest(byte[], int, int)
     */
public void test_digestLB$LILI() throws Exception {
    MyMessageDigest1 md = new MyMessageDigest1("ABC");
    byte[] b = { 1, 2, 3, 4, 5 };
    assertEquals("incorrect result", 0, md.digest(b, 2, 3));
    assertTrue("digest failed", md.runEngineDigest);
    // Regression for Harmony-1148
    md = new MyMessageDigest1();
    final byte[] bytes = new byte[] { 2, 4, 1 };
    try {
        // buf == null
        md.digest(null, 0, 1);
        fail("No expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
    try {
        // offset + len > buf.length
        md.digest(bytes, 0, bytes.length + 1);
        fail("No expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
    try {
        // offset + len > Integer.MAX_VALUE
        md.digest(bytes, Integer.MAX_VALUE, 1);
        fail("No expected IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
    // offset<0 and len<0 are passed to provider
    final int offset = -1;
    final int len = -1;
    final int status = 33;
    md = new MyMessageDigest1("ABC") {

        @Override
        public int engineDigest(byte[] arg0, int arg1, int arg2) {
            assertSame("buf", bytes, arg0);
            assertEquals("offset", offset, arg1);
            assertEquals("len", len, arg2);
            return status;
        }
    };
    assertEquals("returned status", status, md.digest(bytes, offset, len));
    try {
        MessageDigest digest = MessageDigest.getInstance("TestDigest", new TestProvider());
        digest.digest(new byte[5], 0, 5);
        fail("expected DigestException");
    } catch (DigestException e) {
    // ok
    }
}
Also used : DigestException(java.security.DigestException) MyMessageDigest1(org.apache.harmony.security.tests.support.MyMessageDigest1) MessageDigest(java.security.MessageDigest)

Example 19 with DigestException

use of java.security.DigestException in project walle by Meituan-Dianping.

the class V2SchemeSigner method computeContentDigests.

static Map<ContentDigestAlgorithm, byte[]> computeContentDigests(Set<ContentDigestAlgorithm> digestAlgorithms, DataSource[] contents) throws IOException, DigestException {
    // For each digest algorithm the result is computed as follows:
    // 1. Each segment of contents is split into consecutive chunks of 1 MB in size.
    //    The final chunk will be shorter iff the length of segment is not a multiple of 1 MB.
    //    No chunks are produced for empty (zero length) segments.
    // 2. The digest of each chunk is computed over the concatenation of byte 0xa5, the chunk's
    //    length in bytes (uint32 little-endian) and the chunk's contents.
    // 3. The output digest is computed over the concatenation of the byte 0x5a, the number of
    //    chunks (uint32 little-endian) and the concatenation of digests of chunks of all
    //    segments in-order.
    long chunkCountLong = 0;
    for (DataSource input : contents) {
        chunkCountLong += getChunkCount(input.size(), CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES);
    }
    if (chunkCountLong > Integer.MAX_VALUE) {
        throw new DigestException("Input too long: " + chunkCountLong + " chunks");
    }
    int chunkCount = (int) chunkCountLong;
    ContentDigestAlgorithm[] digestAlgorithmsArray = digestAlgorithms.toArray(new ContentDigestAlgorithm[digestAlgorithms.size()]);
    MessageDigest[] mds = new MessageDigest[digestAlgorithmsArray.length];
    byte[][] digestsOfChunks = new byte[digestAlgorithmsArray.length][];
    int[] digestOutputSizes = new int[digestAlgorithmsArray.length];
    for (int i = 0; i < digestAlgorithmsArray.length; i++) {
        ContentDigestAlgorithm digestAlgorithm = digestAlgorithmsArray[i];
        int digestOutputSizeBytes = digestAlgorithm.getChunkDigestOutputSizeBytes();
        digestOutputSizes[i] = digestOutputSizeBytes;
        byte[] concatenationOfChunkCountAndChunkDigests = new byte[5 + chunkCount * digestOutputSizeBytes];
        concatenationOfChunkCountAndChunkDigests[0] = 0x5a;
        setUnsignedInt32LittleEndian(chunkCount, concatenationOfChunkCountAndChunkDigests, 1);
        digestsOfChunks[i] = concatenationOfChunkCountAndChunkDigests;
        String jcaAlgorithm = digestAlgorithm.getJcaMessageDigestAlgorithm();
        try {
            mds[i] = MessageDigest.getInstance(jcaAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(jcaAlgorithm + " MessageDigest not supported", e);
        }
    }
    MessageDigestSink mdSink = new MessageDigestSink(mds);
    byte[] chunkContentPrefix = new byte[5];
    chunkContentPrefix[0] = (byte) 0xa5;
    int chunkIndex = 0;
    // digest to be more efficient because it's presented with all of its input in one go.
    for (DataSource input : contents) {
        long inputOffset = 0;
        long inputRemaining = input.size();
        while (inputRemaining > 0) {
            int chunkSize = (int) Math.min(inputRemaining, CONTENT_DIGESTED_CHUNK_MAX_SIZE_BYTES);
            setUnsignedInt32LittleEndian(chunkSize, chunkContentPrefix, 1);
            for (int i = 0; i < mds.length; i++) {
                mds[i].update(chunkContentPrefix);
            }
            try {
                input.feed(inputOffset, chunkSize, mdSink);
            } catch (IOException e) {
                throw new IOException("Failed to read chunk #" + chunkIndex, e);
            }
            for (int i = 0; i < digestAlgorithmsArray.length; i++) {
                MessageDigest md = mds[i];
                byte[] concatenationOfChunkCountAndChunkDigests = digestsOfChunks[i];
                int expectedDigestSizeBytes = digestOutputSizes[i];
                int actualDigestSizeBytes = md.digest(concatenationOfChunkCountAndChunkDigests, 5 + chunkIndex * expectedDigestSizeBytes, expectedDigestSizeBytes);
                if (actualDigestSizeBytes != expectedDigestSizeBytes) {
                    throw new RuntimeException("Unexpected output size of " + md.getAlgorithm() + " digest: " + actualDigestSizeBytes);
                }
            }
            inputOffset += chunkSize;
            inputRemaining -= chunkSize;
            chunkIndex++;
        }
    }
    Map<ContentDigestAlgorithm, byte[]> result = new HashMap<>(digestAlgorithmsArray.length);
    for (int i = 0; i < digestAlgorithmsArray.length; i++) {
        ContentDigestAlgorithm digestAlgorithm = digestAlgorithmsArray[i];
        byte[] concatenationOfChunkCountAndChunkDigests = digestsOfChunks[i];
        MessageDigest md = mds[i];
        byte[] digest = md.digest(concatenationOfChunkCountAndChunkDigests);
        result.put(digestAlgorithm, digest);
    }
    return result;
}
Also used : HashMap(java.util.HashMap) MessageDigestSink(com.android.apksigner.core.internal.util.MessageDigestSink) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) DataSource(com.android.apksigner.core.util.DataSource) DigestException(java.security.DigestException) MessageDigest(java.security.MessageDigest)

Example 20 with DigestException

use of java.security.DigestException in project walle by Meituan-Dianping.

the class V2SchemeVerifier method verifyIntegrity.

/**
     * Verifies integrity of the APK outside of the APK Signing Block by computing digests of the
     * APK and comparing them against the digests listed in APK Signing Block. The expected digests
     * taken from {@code v2SchemeSignerInfos} of the provided {@code result}.
     */
private static void verifyIntegrity(DataSource beforeApkSigningBlock, DataSource centralDir, ByteBuffer eocd, Set<ContentDigestAlgorithm> contentDigestAlgorithms, Result result) throws IOException {
    if (contentDigestAlgorithms.isEmpty()) {
        // is verified, meaning at least one content digest is known.
        throw new RuntimeException("No content digests found");
    }
    // For the purposes of verifying integrity, ZIP End of Central Directory (EoCD) must be
    // treated as though its Central Directory offset points to the start of APK Signing Block.
    // We thus modify the EoCD accordingly.
    ByteBuffer modifiedEocd = ByteBuffer.allocate(eocd.remaining());
    modifiedEocd.order(ByteOrder.LITTLE_ENDIAN);
    modifiedEocd.put(eocd);
    modifiedEocd.flip();
    ZipUtils.setZipEocdCentralDirectoryOffset(modifiedEocd, beforeApkSigningBlock.size());
    Map<ContentDigestAlgorithm, byte[]> actualContentDigests;
    try {
        actualContentDigests = V2SchemeSigner.computeContentDigests(contentDigestAlgorithms, new DataSource[] { beforeApkSigningBlock, centralDir, new ByteBufferDataSource(modifiedEocd) });
    } catch (DigestException e) {
        throw new RuntimeException("Failed to compute content digests", e);
    }
    if (!contentDigestAlgorithms.equals(actualContentDigests.keySet())) {
        throw new RuntimeException("Mismatch between sets of requested and computed content digests" + " . Requested: " + contentDigestAlgorithms + ", computed: " + actualContentDigests.keySet());
    }
    // in signer blocks.
    for (Result.SignerInfo signerInfo : result.signers) {
        for (Result.SignerInfo.ContentDigest expected : signerInfo.contentDigests) {
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.findById(expected.getSignatureAlgorithmId());
            if (signatureAlgorithm == null) {
                continue;
            }
            ContentDigestAlgorithm contentDigestAlgorithm = signatureAlgorithm.getContentDigestAlgorithm();
            byte[] expectedDigest = expected.getValue();
            byte[] actualDigest = actualContentDigests.get(contentDigestAlgorithm);
            if (!Arrays.equals(expectedDigest, actualDigest)) {
                signerInfo.addError(Issue.V2_SIG_APK_DIGEST_DID_NOT_VERIFY, contentDigestAlgorithm, toHex(expectedDigest), toHex(actualDigest));
                continue;
            }
            signerInfo.verifiedContentDigests.put(contentDigestAlgorithm, actualDigest);
        }
    }
}
Also used : ByteBufferDataSource(com.android.apksigner.core.internal.util.ByteBufferDataSource) ByteBuffer(java.nio.ByteBuffer) DataSource(com.android.apksigner.core.util.DataSource) ByteBufferDataSource(com.android.apksigner.core.internal.util.ByteBufferDataSource) DigestException(java.security.DigestException)

Aggregations

DigestException (java.security.DigestException)31 MessageDigest (java.security.MessageDigest)19 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)15 IOException (java.io.IOException)7 DataSource (com.android.apksigner.core.util.DataSource)3 ByteBuffer (java.nio.ByteBuffer)2 MyMessageDigest1 (org.apache.harmony.security.tests.support.MyMessageDigest1)2 LimitedLengthInputStream (android.content.pm.LimitedLengthInputStream)1 MacAuthenticatedInputStream (android.content.pm.MacAuthenticatedInputStream)1 ParcelFileDescriptor (android.os.ParcelFileDescriptor)1 ByteBufferDataSource (com.android.apksigner.core.internal.util.ByteBufferDataSource)1 MessageDigestSink (com.android.apksigner.core.internal.util.MessageDigestSink)1 BufferedInputStream (java.io.BufferedInputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1 GeneralSecurityException (java.security.GeneralSecurityException)1 SignatureException (java.security.SignatureException)1 HashMap (java.util.HashMap)1