Search in sources :

Example 36 with MessageDigest

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

the class JarVerifier method verify.

private boolean verify(Attributes attributes, String entry, byte[] data, int start, int end, boolean ignoreSecondEndline, boolean ignorable) {
    for (int i = 0; i < DIGEST_ALGORITHMS.length; i++) {
        String algorithm = DIGEST_ALGORITHMS[i];
        String hash = attributes.getValue(algorithm + entry);
        if (hash == null) {
            continue;
        }
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            continue;
        }
        if (ignoreSecondEndline && data[end - 1] == '\n' && data[end - 2] == '\n') {
            md.update(data, start, end - 1 - start);
        } else {
            md.update(data, start, end - start);
        }
        byte[] b = md.digest();
        byte[] hashBytes = hash.getBytes(StandardCharsets.ISO_8859_1);
        return MessageDigest.isEqual(b, Base64.decode(hashBytes));
    }
    return ignorable;
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 37 with MessageDigest

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

the class JarUtils method verifySignature.

/**
     * This method handle all the work with  PKCS7, ASN1 encoding, signature verifying,
     * and certification path building.
     * See also PKCS #7: Cryptographic Message Syntax Standard:
     * http://www.ietf.org/rfc/rfc2315.txt
     * @param signature - the input stream of signature file to be verified
     * @param signatureBlock - the input stream of corresponding signature block file
     * @return array of certificates used to verify the signature file
     * @throws IOException - if some errors occurs during reading from the stream
     * @throws GeneralSecurityException - if signature verification process fails
     */
public static Certificate[] verifySignature(InputStream signature, InputStream signatureBlock) throws IOException, GeneralSecurityException {
    BerInputStream bis = new BerInputStream(signatureBlock);
    ContentInfo info = (ContentInfo) ContentInfo.ASN1.decode(bis);
    SignedData signedData = info.getSignedData();
    if (signedData == null) {
        throw new IOException("No SignedData found");
    }
    Collection<org.apache.harmony.security.x509.Certificate> encCerts = signedData.getCertificates();
    if (encCerts.isEmpty()) {
        return null;
    }
    X509Certificate[] certs = new X509Certificate[encCerts.size()];
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    int i = 0;
    for (org.apache.harmony.security.x509.Certificate encCert : encCerts) {
        final byte[] encoded = encCert.getEncoded();
        final InputStream is = new ByteArrayInputStream(encoded);
        certs[i++] = new VerbatimX509Certificate((X509Certificate) cf.generateCertificate(is), encoded);
    }
    List<SignerInfo> sigInfos = signedData.getSignerInfos();
    SignerInfo sigInfo;
    if (!sigInfos.isEmpty()) {
        sigInfo = sigInfos.get(0);
    } else {
        return null;
    }
    // Issuer
    X500Principal issuer = sigInfo.getIssuer();
    // Certificate serial number
    BigInteger snum = sigInfo.getSerialNumber();
    // Locate the certificate
    int issuerSertIndex = 0;
    for (i = 0; i < certs.length; i++) {
        if (issuer.equals(certs[i].getIssuerDN()) && snum.equals(certs[i].getSerialNumber())) {
            issuerSertIndex = i;
            break;
        }
    }
    if (i == certs.length) {
        // No issuer certificate found
        return null;
    }
    if (certs[issuerSertIndex].hasUnsupportedCriticalExtension()) {
        throw new SecurityException("Can not recognize a critical extension");
    }
    // Get Signature instance
    final String daOid = sigInfo.getDigestAlgorithm();
    final String daName = sigInfo.getDigestAlgorithmName();
    final String deaOid = sigInfo.getDigestEncryptionAlgorithm();
    final String deaName = sigInfo.getDigestEncryptionAlgorithmName();
    String alg = null;
    Signature sig = null;
    if (daOid != null && deaOid != null) {
        alg = daOid + "with" + deaOid;
        try {
            sig = Signature.getInstance(alg);
        } catch (NoSuchAlgorithmException e) {
        }
        // Try to convert to names instead of OID.
        if (sig == null && daName != null && deaName != null) {
            alg = daName + "with" + deaName;
            try {
                sig = Signature.getInstance(alg);
            } catch (NoSuchAlgorithmException e) {
            }
        }
    }
    if (sig == null && deaOid != null) {
        alg = deaOid;
        try {
            sig = Signature.getInstance(alg);
        } catch (NoSuchAlgorithmException e) {
        }
        if (sig == null) {
            alg = deaName;
            try {
                sig = Signature.getInstance(alg);
            } catch (NoSuchAlgorithmException e) {
            }
        }
    }
    // We couldn't find a valid Signature type.
    if (sig == null) {
        return null;
    }
    sig.initVerify(certs[issuerSertIndex]);
    // If the authenticatedAttributes field of SignerInfo contains more than zero attributes,
    // compute the message digest on the ASN.1 DER encoding of the Attributes value.
    // Otherwise, compute the message digest on the data.
    List<AttributeTypeAndValue> atr = sigInfo.getAuthenticatedAttributes();
    byte[] sfBytes = new byte[signature.available()];
    signature.read(sfBytes);
    if (atr == null) {
        sig.update(sfBytes);
    } else {
        sig.update(sigInfo.getEncodedAuthenticatedAttributes());
        // If the authenticatedAttributes field contains the message-digest attribute,
        // verify that it equals the computed digest of the signature file
        byte[] existingDigest = null;
        for (AttributeTypeAndValue a : atr) {
            if (Arrays.equals(a.getType().getOid(), MESSAGE_DIGEST_OID)) {
                if (existingDigest != null) {
                    throw new SecurityException("Too many MessageDigest attributes");
                }
                Collection<?> entries = a.getValue().getValues(ASN1OctetString.getInstance());
                if (entries.size() != 1) {
                    throw new SecurityException("Too many values for MessageDigest attribute");
                }
                existingDigest = (byte[]) entries.iterator().next();
            }
        }
        // must have a message-digest attribute.
        if (existingDigest == null) {
            throw new SecurityException("Missing MessageDigest in Authenticated Attributes");
        }
        MessageDigest md = null;
        if (daOid != null) {
            md = MessageDigest.getInstance(daOid);
        }
        if (md == null && daName != null) {
            md = MessageDigest.getInstance(daName);
        }
        if (md == null) {
            return null;
        }
        byte[] computedDigest = md.digest(sfBytes);
        if (!Arrays.equals(existingDigest, computedDigest)) {
            throw new SecurityException("Incorrect MD");
        }
    }
    if (!sig.verify(sigInfo.getEncryptedDigest())) {
        throw new SecurityException("Incorrect signature");
    }
    return createChain(certs[issuerSertIndex], certs);
}
Also used : ASN1OctetString(org.apache.harmony.security.asn1.ASN1OctetString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateFactory(java.security.cert.CertificateFactory) ContentInfo(org.apache.harmony.security.pkcs7.ContentInfo) BerInputStream(org.apache.harmony.security.asn1.BerInputStream) MessageDigest(java.security.MessageDigest) SignedData(org.apache.harmony.security.pkcs7.SignedData) BerInputStream(org.apache.harmony.security.asn1.BerInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) AttributeTypeAndValue(org.apache.harmony.security.x501.AttributeTypeAndValue) SignerInfo(org.apache.harmony.security.pkcs7.SignerInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 38 with MessageDigest

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

the class MessageDigest2Test method test_getProvider.

/**
     * java.security.MessageDigest#getProvider()
     */
public void test_getProvider() throws Exception {
    for (Entry<Provider, List<String>> e : digestAlgs.entrySet()) {
        for (String algorithm : e.getValue()) {
            MessageDigest md = MessageDigest.getInstance(algorithm, e.getKey().getName());
            assertNotNull("provider is null", md.getProvider());
        }
    }
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) MessageDigest(java.security.MessageDigest) Provider(java.security.Provider)

Example 39 with MessageDigest

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

the class MessageDigest2Test method test_clone.

/**
     * java.security.MessageDigest#clone()
     */
public void test_clone() throws Exception {
    for (Entry<Provider, List<String>> e : digestAlgs.entrySet()) {
        for (String algorithm : e.getValue()) {
            MessageDigest d1 = MessageDigest.getInstance(algorithm, e.getKey().getName());
            for (byte b = 0; b < 84; b++) {
                d1.update(b);
            }
            MessageDigest d2 = (MessageDigest) d1.clone();
            d1.update((byte) 1);
            d2.update((byte) 1);
            assertTrue("cloned hash differs from original for algorithm " + algorithm, MessageDigest.isEqual(d1.digest(), d2.digest()));
        }
    }
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) MessageDigest(java.security.MessageDigest) Provider(java.security.Provider)

Example 40 with MessageDigest

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

the class MessageDigest2Test method test_digest$B.

/**
     * java.security.MessageDigest#digest(byte[])
     */
public void test_digest$B() throws Exception {
    for (Entry<Provider, List<String>> e : digestAlgs.entrySet()) {
        for (String algorithm : e.getValue()) {
            MessageDigest digest = MessageDigest.getInstance(algorithm, e.getKey().getName());
            assertNotNull(digest);
            digest.digest(AR1);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) MessageDigest(java.security.MessageDigest) Provider(java.security.Provider)

Aggregations

MessageDigest (java.security.MessageDigest)1237 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)613 IOException (java.io.IOException)176 UnsupportedEncodingException (java.io.UnsupportedEncodingException)102 BigInteger (java.math.BigInteger)101 InputStream (java.io.InputStream)72 FileInputStream (java.io.FileInputStream)70 File (java.io.File)62 DigestInputStream (java.security.DigestInputStream)61 Test (org.junit.Test)61 ByteArrayOutputStream (java.io.ByteArrayOutputStream)51 DigestOutputStream (java.security.DigestOutputStream)45 ArrayList (java.util.ArrayList)37 ByteArrayInputStream (java.io.ByteArrayInputStream)31 X509Certificate (java.security.cert.X509Certificate)29 OutputStream (java.io.OutputStream)28 GeneralSecurityException (java.security.GeneralSecurityException)25 Cipher (javax.crypto.Cipher)25 SecretKeySpec (javax.crypto.spec.SecretKeySpec)25 Provider (java.security.Provider)22