Esempio n. 1
0
 /**
  * Checks whether or not the {@link #digest} supports cloning.
  *
  * @return True if so, false otherwise.
  */
 private boolean supportsClone() {
   try {
     digest.clone();
     return true;
   } catch (CloneNotSupportedException e) {
     return false;
   }
 }
Esempio n. 2
0
 public static String getMD5(byte[] bytes) {
   try {
     MessageDigest md5 = (MessageDigest) md5Instance.clone();
     return ByteUtils.getHexString(md5.digest(bytes));
   } catch (CloneNotSupportedException e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 3
0
 public static byte[] digest(byte[] bytes) {
   try {
     MessageDigest md5 = (MessageDigest) md5Instance.clone();
     return md5.digest(bytes);
   } catch (CloneNotSupportedException e) {
     throw new RuntimeException(e);
   }
 }
 public static long digest(String configText, String zoneId) {
   try {
     String target = configText + " " + zoneId;
     byte[] digest = ((MessageDigest) md5.clone()).digest(target.getBytes(UTF_8));
     return ByteBuffer.wrap(digest).getLong(0);
   } catch (CloneNotSupportedException ex) {
     throw new RuntimeException(ex);
   }
 }
Esempio n. 5
0
 static {
   try {
     md5Instance = MessageDigest.getInstance("MD5");
     md5Instance.clone(); // test cloneability
   } catch (NoSuchAlgorithmException e) {
     throw new RuntimeException(e);
   } catch (CloneNotSupportedException e) {
     throw new RuntimeException(e);
   }
 }
 /** Resets the wrapped input stream and the in progress message digest. */
 @Override
 public void reset() throws IOException {
   super.reset();
   if (digestLastMarked != null) {
     try {
       digest = (MessageDigest) digestLastMarked.clone();
     } catch (CloneNotSupportedException e) { // should never occur
       throw new IllegalStateException("unexpected", e);
     }
   }
 }
 @Override
 public void mark(int readlimit) {
   super.mark(readlimit);
   if (markSupported()) {
     try {
       digestLastMarked = (MessageDigest) digest.clone();
     } catch (CloneNotSupportedException e) { // should never occur
       throw new IllegalStateException("unexpected", e);
     }
   }
 }
Esempio n. 8
0
 /**
  * Begins a new hash code computation by returning an initialized, stateful {@link
  * MessageDigestHasher} instance that is ready to receive data.
  */
 MessageDigestHasher newHasher() {
   if (supportsClone) {
     try {
       return new SHA256HashFunction.MessageDigestHasher((MessageDigest) digest.clone(), bytes);
     } catch (CloneNotSupportedException e) {
       // falls through
     }
   }
   return new SHA256HashFunction.MessageDigestHasher(
       getMessageDigest(digest.getAlgorithm()), bytes);
 }
 @Override
 public Hasher newHasher() {
   if (supportsClone) {
     try {
       return new MessageDigestHasher((MessageDigest) prototype.clone(), bytes);
     } catch (CloneNotSupportedException e) {
       // falls through
     }
   }
   return new MessageDigestHasher(getMessageDigest(prototype.getAlgorithm()), bytes);
 }
Esempio n. 10
0
 public static byte[] md5digest(String key) {
   if (key == null) {
     return null;
   }
   MessageDigest md5;
   try {
     md5 = (MessageDigest) md5Digest.clone();
   } catch (CloneNotSupportedException e) {
     throw new RuntimeException("clone of MD5 not supported", e);
   }
   md5.update(key.getBytes());
   return md5.digest();
 }
Esempio n. 11
0
  @Override
  public String getValue() {

    // Clone the digest so we can pad current value for output
    MessageDigest tmpDigest;
    try {
      tmpDigest = (MessageDigest) digest.clone();
    } catch (CloneNotSupportedException e) {
      throw new RuntimeException("Clone failed", e);
    }

    byte[] currDigest = tmpDigest.digest();

    // convert to hex string
    BigInteger bigInt = new BigInteger(1, currDigest);
    return String.format("%0" + (currDigest.length << 1) + "x", bigInt);
  }
Esempio n. 12
0
 @Override
 public void processFile(String data) throws Exception {
   byte[] hash = ((MessageDigest) messageDigest.clone()).digest(data.getBytes("UTF-8"));
   if (seen.add(new BigInteger(hash))) {
     XtextResourceSet resourceSet = resourceSetProvider.get();
     resourceSet.setClasspathURIContext(classLoader);
     XtendFile file = parseHelper.parse(data, resourceSet);
     if (file != null) {
       try {
         XtextResource resource = (XtextResource) file.eResource();
         ITextRegionAccess regions = regionBuilder.get().forNodeModel(resource).create();
         FormatterRequest request = new FormatterRequest().setTextRegionAccess(regions);
         request.setExceptionHandler(ExceptionAcceptor.IGNORING);
         formatter.format(request);
       } catch (Exception e) {
         e.printStackTrace();
         ComparisonFailure error = new ComparisonFailure(e.getMessage(), data, "");
         error.setStackTrace(e.getStackTrace());
         throw error;
       }
     }
   }
 }
  /**
   * The ServerHelloDone message is sent by the server to indicate the end of the ServerHello and
   * associated messages. The client prepares all necessary messages (depending on server's previous
   * flight) and returns the next flight.
   *
   * @return the client's next flight to be sent.
   * @throws HandshakeException
   */
  private DTLSFlight receivedServerHelloDone(ServerHelloDone message) throws HandshakeException {
    DTLSFlight flight = new DTLSFlight();
    if (serverHelloDone != null && (serverHelloDone.getMessageSeq() == message.getMessageSeq())) {
      // discard duplicate message
      return flight;
    }
    serverHelloDone = message;

    /*
     * All possible handshake messages sent in this flight. Used to compute
     * handshake hash.
     */
    CertificateMessage clientCertificate = null;
    ClientKeyExchange clientKeyExchange = null;
    CertificateVerify certificateVerify = null;

    /*
     * First, if required by server, send Certificate.
     */
    if (certificateRequest != null) {
      // TODO load the client's certificate according to the allowed
      // parameters in the CertificateRequest
      clientCertificate = new CertificateMessage(certificates, session.sendRawPublicKey());

      flight.addMessage(wrapMessage(clientCertificate));
    }

    /*
     * Second, send ClientKeyExchange as specified by the key exchange
     * algorithm.
     */
    byte[] premasterSecret;
    switch (keyExchange) {
      case EC_DIFFIE_HELLMAN:
        clientKeyExchange = new ECDHClientKeyExchange(ecdhe.getPublicKey());
        premasterSecret = ecdhe.getSecret(ephemeralServerPublicKey).getEncoded();

        generateKeys(premasterSecret);

        break;

      case PSK:
        String identity = ScProperties.std.getProperty("PSK_IDENTITY");
        clientKeyExchange = new PSKClientKeyExchange(identity);
        byte[] psk = sharedKeys.get(identity);

        if (psk == null) {
          AlertMessage alert =
              new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
          throw new HandshakeException(
              "No preshared secret found for identity: " + identity, alert);
        }

        LOGGER.info("Using PSK identity: " + identity);

        premasterSecret = generatePremasterSecretFromPSK(psk);
        generateKeys(premasterSecret);

        break;

      case NULL:
        clientKeyExchange = new NULLClientKeyExchange();

        // We assume, that the premaster secret is empty
        generateKeys(new byte[] {});
        break;

      default:
        AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
        throw new HandshakeException("Unknown key exchange algorithm: " + keyExchange, alert);
    }
    flight.addMessage(wrapMessage(clientKeyExchange));

    /*
     * Third, send CertificateVerify message if necessary.
     */
    if (certificateRequest != null) {
      // prepare handshake messages
      handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, clientHello.toByteArray());
      handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, serverHello.toByteArray());
      handshakeMessages =
          ByteArrayUtils.concatenate(handshakeMessages, serverCertificate.toByteArray());
      handshakeMessages =
          ByteArrayUtils.concatenate(handshakeMessages, serverKeyExchange.toByteArray());
      handshakeMessages =
          ByteArrayUtils.concatenate(handshakeMessages, certificateRequest.toByteArray());
      handshakeMessages =
          ByteArrayUtils.concatenate(handshakeMessages, serverHelloDone.toByteArray());
      handshakeMessages =
          ByteArrayUtils.concatenate(handshakeMessages, clientCertificate.toByteArray());
      handshakeMessages =
          ByteArrayUtils.concatenate(handshakeMessages, clientKeyExchange.toByteArray());

      // TODO make sure, that signature is supported
      SignatureAndHashAlgorithm signatureAndHashAlgorithm =
          certificateRequest.getSupportedSignatureAlgorithms().get(0);
      certificateVerify =
          new CertificateVerify(signatureAndHashAlgorithm, privateKey, handshakeMessages);

      flight.addMessage(wrapMessage(certificateVerify));
    }

    /*
     * Fourth, send ChangeCipherSpec
     */
    ChangeCipherSpecMessage changeCipherSpecMessage = new ChangeCipherSpecMessage();
    flight.addMessage(wrapMessage(changeCipherSpecMessage));
    setCurrentWriteState();
    session.incrementWriteEpoch();

    /*
     * Fifth, send the finished message.
     */
    try {
      // create hash of handshake messages
      // can't do this on the fly, since there is no explicit ordering of
      // messages

      MessageDigest md = MessageDigest.getInstance("SHA-256");
      md.update(clientHello.toByteArray());
      md.update(serverHello.toByteArray());
      if (serverCertificate != null) {
        md.update(serverCertificate.toByteArray());
      }
      if (serverKeyExchange != null) {
        md.update(serverKeyExchange.toByteArray());
      }
      if (certificateRequest != null) {
        md.update(certificateRequest.toByteArray());
      }
      md.update(serverHelloDone.toByteArray());

      if (clientCertificate != null) {
        md.update(clientCertificate.toByteArray());
      }
      md.update(clientKeyExchange.toByteArray());

      if (certificateVerify != null) {
        md.update(certificateVerify.toByteArray());
      }

      MessageDigest mdWithClientFinished = null;
      try {
        mdWithClientFinished = (MessageDigest) md.clone();
      } catch (CloneNotSupportedException e) {
        LOGGER.severe("Clone not supported.");
        e.printStackTrace();
      }

      handshakeHash = md.digest();
      Finished finished = new Finished(getMasterSecret(), isClient, handshakeHash);
      flight.addMessage(wrapMessage(finished));

      // compute handshake hash with client's finished message also
      // included, used for server's finished message
      mdWithClientFinished.update(finished.toByteArray());
      handshakeHash = mdWithClientFinished.digest();

    } catch (NoSuchAlgorithmException e) {
      LOGGER.severe("No such Message Digest Algorithm available.");
      e.printStackTrace();
    }

    return flight;
  }