Throw an exception if the MD5 checksums included in the ReceiveMessageResult do not match the
client-side calculation on the received messages.
340192
private static void receiveMessageResultMd5Check(ReceiveMessageResult receiveMessageResult) {
        if (receiveMessageResult.getMessages() != null) {
            for (Message messageReceived : receiveMessageResult.getMessages()) {
                String messageBody = messageReceived.getBody();
                String bodyMd5Returned = messageReceived.getMD5OfBody();
                String clientSideBodyMd5 = calculateMessageBodyMd5(messageBody);
                if (!clientSideBodyMd5.equals(bodyMd5Returned)) {
                    throw new AmazonClientException(String.format(MD5_MISMATCH_ERROR_MESSAGE, MESSAGE_BODY,
                            clientSideBodyMd5, bodyMd5Returned));
                }

                Map<String, MessageAttributeValue> messageAttr = messageReceived.getMessageAttributes();
                if (messageAttr != null && !messageAttr.isEmpty()) {
                    String attrMd5Returned = messageReceived.getMD5OfMessageAttributes();
                    String clientSideAttrMd5 = calculateMessageAttributesMd5(messageAttr);
                    if (!clientSideAttrMd5.equals(attrMd5Returned)) {
                        throw new AmazonClientException(String.format(MD5_MISMATCH_ERROR_MESSAGE, MESSAGE_ATTRIBUTES,
                                clientSideAttrMd5, attrMd5Returned));
                    }
                }
            }
        }
    }
35742
private void verifySum(long errPos) throws ChecksumException {
    long crc = getChecksum();
    long sumValue = sum.getValue();
    sum.reset();
    if (crc != sumValue) {
      throw new ChecksumException(
          "Checksum error: "+file+" at "+errPos, errPos);
    }
  }
1160603
@Override
    public UndeliverableReturnCode handleUndeliverableMessage(
                                                              SIMPMessage msg,
                                                              int exceptionReason,
                                                              String[] exceptionInserts,
                                                              TransactionCommon tran)
                    throws SIIncorrectCallException, SIResourceException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "handleUndeliverableMessage",
                        new Object[] { msg, new Integer(exceptionReason), exceptionInserts });

        UndeliverableReturnCode undeliverableReturnCode =
                        _targetDestinationHandler.handleUndeliverableMessage(msg, exceptionReason, exceptionInserts, tran);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "handleUndeliverableMessage", undeliverableReturnCode);

        return undeliverableReturnCode;
    }
549170
def grab_checksums_file(entry):
    """"""
    http_url = convert_ftp_url(entry['ftp_path'])
    full_url = '{}/md5checksums.txt'.format(http_url)
    req = requests.get(full_url)
    return req.text
1054892
private static void sendMessageBatchOperationMd5Check(SendMessageBatchRequest sendMessageBatchRequest,
                                                          SendMessageBatchResult sendMessageBatchResult) {
        Map<String, SendMessageBatchRequestEntry> idToRequestEntryMap = new HashMap<String, SendMessageBatchRequestEntry>();
        if (sendMessageBatchRequest.getEntries() != null) {
            for (SendMessageBatchRequestEntry entry : sendMessageBatchRequest.getEntries()) {
                idToRequestEntryMap.put(entry.getId(), entry);
            }
        }

        if (sendMessageBatchResult.getSuccessful() != null) {
            for (SendMessageBatchResultEntry entry : sendMessageBatchResult.getSuccessful()) {
                String messageBody = idToRequestEntryMap.get(entry.getId()).getMessageBody();
                String bodyMd5Returned = entry.getMD5OfMessageBody();
                String clientSideBodyMd5 = calculateMessageBodyMd5(messageBody);
                if (!clientSideBodyMd5.equals(bodyMd5Returned)) {
                    throw new AmazonClientException(String.format(MD5_MISMATCH_ERROR_MESSAGE_WITH_ID, MESSAGE_BODY,
                            entry.getId(), clientSideBodyMd5, bodyMd5Returned));
                }

                Map<String, MessageAttributeValue> messageAttr = idToRequestEntryMap.get(entry.getId())
                        .getMessageAttributes();
                if (messageAttr != null && !messageAttr.isEmpty()) {
                    String attrMd5Returned = entry.getMD5OfMessageAttributes();
                    String clientSideAttrMd5 = calculateMessageAttributesMd5(messageAttr);
                    if (!clientSideAttrMd5.equals(attrMd5Returned)) {
                        throw new AmazonClientException(String.format(MD5_MISMATCH_ERROR_MESSAGE_WITH_ID,
                                MESSAGE_ATTRIBUTES, entry.getId(), clientSideAttrMd5, attrMd5Returned));
                    }
                }
            }
        }
    }
860139
private void checkAddresses(Message m, Address[] addresses)
            throws MessagingException, SendFailedException {

        if ( isNullOrEmpty((Object[]) addresses)
                && isNullOrEmpty((Object[]) m.getRecipients(Message.RecipientType.TO))
                && isNullOrEmpty((Object[]) m.getRecipients(Message.RecipientType.CC))
                && isNullOrEmpty((Object[]) m.getRecipients(Message.RecipientType.BCC)) ) {
            throw new SendFailedException("No recipient addresses");
        }

        // Make sure all addresses are internet addresses
        Set<Address> invalid = new HashSet<Address>();
        for ( Address[] recipients : new Address[][] {
                m.getRecipients(Message.RecipientType.TO),
                m.getRecipients(Message.RecipientType.CC),
                m.getRecipients(Message.RecipientType.BCC),
                addresses } ) {
            if ( !isNullOrEmpty(recipients) ) {
                for ( Address a : recipients ) {
                    if ( !(a instanceof InternetAddress) ) {
                        invalid.add(a);
                    }
                }
            }
        }

        if ( !invalid.isEmpty() ) {
            Address[] sent = new Address[0];
            Address[] unsent = new Address[0];
            super.notifyTransportListeners(TransportEvent.MESSAGE_NOT_DELIVERED, sent, unsent,
                    invalid.toArray(new Address[invalid.size()]), m);
            throw new SendFailedException("AWS Mail Service can only send to InternetAddresses");
        }
    }
82178
private void checkHashes(Dependency dependency, String sha1, String sha256, String md5) throws FileNotFoundException {
        final String md5sum = dependency.getMd5sum();
        if (!md5.equals(md5sum)) {
            throw new FileNotFoundException("Artifact found by API is not matching the md5 "
                    + "of the artifact (repository hash is " + md5 + WHILE_ACTUAL_IS + md5sum + ") !");
        }
        final String sha1sum = dependency.getSha1sum();
        if (!sha1.equals(sha1sum)) {
            throw new FileNotFoundException("Artifact found by API is not matching the SHA1 "
                    + "of the artifact (repository hash is " + sha1 + WHILE_ACTUAL_IS + sha1sum + ") !");
        }
        final String sha256sum = dependency.getSha256sum();
        if (sha256 != null && !sha256.equals(sha256sum)) {
            throw new FileNotFoundException("Artifact found by API is not matching the SHA-256 "
                    + "of the artifact (repository hash is " + sha256 + WHILE_ACTUAL_IS + sha256sum + ") !");
        }
    }
1141656
public synchronized void handleMessage(ChaincodeMessage message) throws Exception {

		if (message.getType() == ChaincodeMessage.Type.KEEPALIVE){
			logger.debug(String.format("[%s] Recieved KEEPALIVE message, do nothing",
					shortID(message)));
			// Received a keep alive message, we don't do anything with it for now
			// and it does not touch the state machine
				return;
		}

		logger.debug(String.format("[%s]Handling ChaincodeMessage of type: %s(state:%s)",
				shortID(message), message.getType(), fsm.current()));

		if (fsm.eventCannotOccur(message.getType().toString())) {
			String errStr = String.format("[%s]Chaincode handler org.hyperledger.fabric.java.fsm cannot handle message (%s) with payload size (%d) while in state: %s",
					message.getTxid(), message.getType(), message.getPayload().size(), fsm.current());
			ByteString payload = ByteString.copyFromUtf8(errStr);
			ChaincodeMessage errormessage = ChaincodeMessage.newBuilder()
					.setType(ERROR)
					.setPayload(payload)
					.setTxid(message.getTxid())
					.build();
			serialSend(errormessage);
			throw new RuntimeException(errStr);
		}

		// Filter errors to allow NoTransitionError and CanceledError
		// to not propagate for cases where embedded Err == nil.
		try {
			fsm.raiseEvent(message.getType().toString(), message);
		} catch (NoTransitionException e) {
			if (e.error != null) throw e;
			logger.debug("["+ shortID(message)+"]Ignoring NoTransitionError");
		} catch (CancelledException e) {
			if (e.error != null) throw e;
			logger.debug("["+ shortID(message)+"]Ignoring CanceledError");
		}
	}
1325206
private String calculateChecksum(File file) throws IOException {
		InputStream is = new FileInputStream(file);
		return DigestUtils.md5Hex(is);
	}
659340
def _decode_received(self, msg):
        """"""
        if not isinstance(msg, six.binary_type):
            # already decoded - do nothing
            return msg
        # only decode from utf-8 if message is not binary data
        type = six.byte2int(msg[0:1])
        if type >= 48:  # no binary
            return msg.decode('utf-8')
        # binary message, don't try to decode
        return msg
768876
private static String md5(byte[] buffer) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(buffer);
            byte[] digest = md.digest();
            return new String(FlexBase64.encodeBytes(digest, 0, digest.length, false), StandardCharsets.US_ASCII);
        } catch (NoSuchAlgorithmException e) {
            // Should never happen
            throw new InternalError("MD5 not supported on this platform");
        }
    }
738622
public boolean checkInputMessageNumbering(SccpConnectionImpl conn, SequenceNumber sendSequenceNumber,
                                              SequenceNumber receiveSequenceNumber) throws Exception {
        if (sendSequenceNumber != null) {
            if (expectingFirstMessageInputAfterInit && !sendSequenceNumber.equals(new SequenceNumberImpl(0))) {
                // local procedure error
                conn.reset(new ResetCauseImpl(ResetCauseValue.MESSAGE_OUT_OF_ORDER_INCORRECT_PS));
                return false;

            } else if (sendSequenceNumber.equals(sendSequenceNumberExpectedAtInput) && inputWindow.contains(sendSequenceNumber)) {
                sendSequenceNumberExpectedAtInput = sendSequenceNumberExpectedAtInput.nextNumber();

            } else {
                if (!inputWindow.contains(sendSequenceNumber)) {
                    conn.reset(new ResetCauseImpl(ResetCauseValue.REMOTE_PROCEDURE_ERROR_MESSAGE_OUT_OF_WINDOW));

                } else if (!sendSequenceNumber.equals(sendSequenceNumberExpectedAtInput)) {
                    // local procedure error
                    conn.resetSection(new ResetCauseImpl(ResetCauseValue.MESSAGE_OUT_OF_ORDER_INCORRECT_PS));
                }
                return false;
            }
        }

        if (rangeContains(lastReceiveSequenceNumberReceived, this.sendSequenceNumber.nextNumber(), receiveSequenceNumber)) {
            outputWindow.setLowerEdge(receiveSequenceNumber);
        } else {
            conn.resetSection(new ResetCauseImpl(ResetCauseValue.MESSAGE_OUT_OF_ORDER_INCORRECT_PS));
            return false;
        }

        lastReceiveSequenceNumberReceived = receiveSequenceNumber;
        expectingFirstMessageInputAfterInit = false;
        return true;
    }
631539
public static String getMD5(String md5Salt) {
		try {
			MessageDigest md = MessageDigest.getInstance(MD5);
			byte[] array = md.digest(md5Salt.getBytes(UTF8));
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
			}
			return sb.toString();
		} catch (java.security.NoSuchAlgorithmException e) {
			LOG.error(e.getMessage());
		} catch (UnsupportedEncodingException e) {
			LOG.error(e.getMessage());
		}
		return null;
	}
1058190
public void verifyMIC(byte[] inTok, int tokOff, int tokLen, // mic
                          byte[] inMsg, int msgOff, int msgLen, // real msg
                          MessageProp prop)
        throws GSSException {
        throw new GSSException(GSSException.UNAVAILABLE);
/*TODO

        checkContext();

        logger.debug("enter verifyMic");

        SSLCipherState st = this.conn.getReadCipherState();
        SSLCipherSuite cs = st.getCipherSuite();

        logger.debug("digest algorithm: " + cs.getDigestAlg());

        if (tokLen != (GSI_MESSAGE_DIGEST_PADDING + cs.getDigestOutputLength())) {
            throw new GlobusGSSException(GSSException.DEFECTIVE_TOKEN,
                                         GlobusGSSException.TOKEN_FAIL,
                                         "tokenFail00",
                                         new Object[] {new Integer(tokLen),
                                                       new Integer(GSI_MESSAGE_DIGEST_PADDING +
                                                                   cs.getDigestOutputLength())});
        }

        int bufLen = SSLUtil.toInt(inTok, tokOff+GSI_SEQUENCE_SIZE);
        if (bufLen != msgLen) {
            throw new GlobusGSSException(GSSException.DEFECTIVE_TOKEN,
                                         GlobusGSSException.TOKEN_FAIL,
                                         "tokenFail01",
                                         new Object[] {new Integer(msgLen), new Integer(bufLen)});
        }

        int pad_ct = (cs.getDigestOutputLength()==16) ? 48 : 40;

        byte [] digest = null;

        try {
            MessageDigest md =
                MessageDigest.getInstance(cs.getDigestAlg());

            md.update(st.getMacKey());
            for(int i=0;i<pad_ct;i++) {
                md.update(SSLHandshake.pad_1);
            }
            md.update(inTok, tokOff, GSI_MESSAGE_DIGEST_PADDING);
            md.update(inMsg, msgOff, msgLen);

            digest = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        byte [] token = new byte[tokLen-GSI_MESSAGE_DIGEST_PADDING];
        System.arraycopy(inTok, tokOff+GSI_MESSAGE_DIGEST_PADDING, token, 0, token.length);

        if (!Arrays.equals(digest, token)) {
            throw new GlobusGSSException(GSSException.BAD_MIC,
                                         GlobusGSSException.BAD_MIC,
                                         "tokenFail02");
        }

        long tokSeq = SSLUtil.toLong(inTok, tokOff);
        long readSeq = this.conn.getReadSequence();
        long seqTest = tokSeq - readSeq;

        logger.debug("Token seq#   : " + tokSeq);
        logger.debug("Current seq# : " + readSeq);

        if (seqTest > 0) {
            // gap token
            throw new GSSException(GSSException.GAP_TOKEN);
        } else if (seqTest < 0) {
            // old token
            throw new GSSException(GSSException.OLD_TOKEN);
        } else {
            this.conn.incrementReadSequence();
        }

        if (prop != null) {
            prop.setPrivacy(false);
            prop.setQOP(0);
        }

        logger.debug("exit verifyMic");
*/
    }
327004
private void validateTrackerResponse(TrackerMessage message)
          throws AnnounceException {
    if (message instanceof ErrorMessage) {
      throw new AnnounceException(((ErrorMessage) message).getReason());
    }

    if (message instanceof UDPTrackerMessage &&
            (((UDPTrackerMessage) message).getTransactionId() != this.transactionId)) {
      throw new AnnounceException("Invalid transaction ID!");
    }
  }
1088960
private static String md5Hex(String message) {
        try {
            final MessageDigest md = MessageDigest.getInstance("MD5");
            final byte[] array = md.digest(message.getBytes("UTF-8"));
            final StringBuilder sb = new StringBuilder();
            for (final byte b : array) {
                sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
33406
private static String calculateMessageBodyMd5(String messageBody) {
        if (log.isDebugEnabled()) {
            log.debug("Message body: " + messageBody);
        }
        byte[] expectedMd5;
        try {
            expectedMd5 = Md5Utils.computeMD5Hash(messageBody.getBytes(UTF8));
        } catch (Exception e) {
            throw new AmazonClientException("Unable to calculate the MD5 hash of the message body. " + e.getMessage(),
                    e);
        }
        String expectedMd5Hex = BinaryUtils.toHex(expectedMd5);
        if (log.isDebugEnabled()) {
            log.debug("Expected  MD5 of message body: " + expectedMd5Hex);
        }
        return expectedMd5Hex;
    }