Tabnine Logo
MessageDigest
Code IndexAdd Tabnine to your IDE (free)

How to use
MessageDigest
in
java.security

Best Java code snippets using java.security.MessageDigest (Showing top 20 results out of 35,595)

Refine searchRefine arrow

  • BigInteger
  • InputStream
  • FileInputStream
  • OutputStream
  • DigestInputStream
  • FileOutputStream
  • X509Certificate
origin: smuyyh/BookReader

public static String checkSum(String path) {
  String checksum = null;
  try {
    FileInputStream fis = new FileInputStream(path);
    MessageDigest md = MessageDigest.getInstance("MD5");
    //Using MessageDigest update() method to provide input
    byte[] buffer = new byte[8192];
    int numOfBytesRead;
    while ((numOfBytesRead = fis.read(buffer)) > 0) {
      md.update(buffer, 0, numOfBytesRead);
    }
    byte[] hash = md.digest();
    checksum = new BigInteger(1, hash).toString(16); //don't use this, truncates leading zero
  } catch (IOException | NoSuchAlgorithmException ignored) {
  }
  assert checksum != null;
  return checksum.trim();
}
origin: stackoverflow.com

 String plaintext = "your text here";
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
 hashtext = "0"+hashtext;
}
origin: stackoverflow.com

 import java.security.*;

..

byte[] bytesOfMessage = yourString.getBytes("UTF-8");

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
origin: apache/incubator-dubbo

private byte[] md5(String value) {
  MessageDigest md5;
  try {
    md5 = MessageDigest.getInstance("MD5");
  } catch (NoSuchAlgorithmException e) {
    throw new IllegalStateException(e.getMessage(), e);
  }
  md5.reset();
  byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
  md5.update(bytes);
  return md5.digest();
}
origin: stackoverflow.com

 MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(Paths.get("file.txt"));
   DigestInputStream dis = new DigestInputStream(is, md)) 
{
 /* Read decorated stream (dis) to EOF as normal... */
}
byte[] digest = md.digest();
origin: stackoverflow.com

MessageDigest digest;
try {
  digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
  Log.e(TAG, "Exception while getting digest", e);
  is = new FileInputStream(updateFile);
} catch (FileNotFoundException e) {
  Log.e(TAG, "Exception while getting FileInputStream", e);
int read;
try {
  while ((read = is.read(buffer)) > 0) {
    digest.update(buffer, 0, read);
  byte[] md5sum = digest.digest();
  BigInteger bigInt = new BigInteger(1, md5sum);
  String output = bigInt.toString(16);
} finally {
  try {
    is.close();
  } catch (IOException e) {
    Log.e(TAG, "Exception on closing MD5 input stream", e);
origin: apache/usergrid

InputStream in = new FileInputStream( file );
KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load( in, passphrase );
in.close();
MessageDigest sha1 = MessageDigest.getInstance( "SHA1" );
MessageDigest md5 = MessageDigest.getInstance( "MD5" );
for ( int i = 0; i < chain.length; i++ ) {
  X509Certificate cert = chain[i];
  LOG.debug( " " + ( i + 1 ) + " Subject " + cert.getSubjectDN() );
  LOG.debug( "   Issuer  " + cert.getIssuerDN() );
  sha1.update( cert.getEncoded() );
  LOG.debug( "   sha1    " + toHexString( sha1.digest() ) );
  md5.update( cert.getEncoded() );
  LOG.debug( "   md5     " + toHexString( md5.digest() ) );
OutputStream out = new FileOutputStream( "jssecacerts" );
ks.store( out, passphrase );
out.close();
origin: stackoverflow.com

out.write('i');
out.write(Long.toString(value).getBytes("US-ASCII"));
out.write('e');
MessageDigest sha1;
try {
  sha1 = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
  throw new Error("SHA1 not supported");
InputStream in = new FileInputStream(file);
ByteArrayOutputStream pieces = new ByteArrayOutputStream();
byte[] bytes = new byte[pieceLength];
int pieceByteCount  = 0, readCount = in.read(bytes, 0, pieceLength);
while (readCount != -1) {
  pieceByteCount += readCount;
  sha1.update(bytes, 0, readCount);
  if (pieceByteCount == pieceLength) {
    pieceByteCount = 0;
    pieces.write(sha1.digest());
  readCount = in.read(bytes, 0, pieceLength-pieceByteCount);
in.close();
if (pieceByteCount > 0)
  pieces.write(sha1.digest());
return pieces.toByteArray();
origin: cSploit/android

mNotificationManager.notify(NOTIFICATION_ID,mBuilder.build());
md5 = (mCurrentTask.md5!=null  ? MessageDigest.getInstance("MD5") : null);
sha1= (mCurrentTask.sha1!=null ? MessageDigest.getInstance("SHA-1") : null);
buffer = new byte[4096];
file = new File(mCurrentTask.path);
writer = new FileOutputStream(file);
reader = connection.getInputStream();
while( mRunning && (read = reader.read(buffer)) != -1 ) {
 writer.write(buffer, 0, read);
 if(md5!=null)
  md5.update(buffer, 0, read);
 if(sha1!=null)
  sha1.update(buffer, 0, read);
 if (md5 != null && !mCurrentTask.md5.equals(digest2string(md5.digest()))) {
  throw new KeyException("wrong MD5");
 } else if (sha1 != null && !mCurrentTask.sha1.equals(digest2string(sha1.digest()))) {
  throw new KeyException("wrong SHA-1");
origin: i2p/i2p.i2p

boolean rv = false;
try {
  in = new BufferedInputStream(new FileInputStream(_file));
  in.mark(10);
  in.reset();
  MessageDigest md = _sigType.getDigestInstance();
  DigestInputStream din = new DigestInputStream(in, md);
  in = din;
  if (!_headerVerified)
      throw new EOFException();
    if (migrateTo != null)  // else verify only
      out.write(buf, 0, read);
    tot += read;
    byte[] sha = md.digest();
    din.on(false);
    Signature signature = new Signature(_sigType);
    signature.readBytes(in);
      out.flush();
      out.getFD().sync();
    } catch (IOException ioe) {}
    try { out.close(); } catch (IOException ioe) {}
origin: googleapis/google-cloud-java

tmpArchive.deleteOnExit();
MessageDigest digest = MessageDigest.getInstance("SHA-256");
try (InputStream is = component.getSource().openStream();
  FileOutputStream os = new FileOutputStream(tmpArchive)) {
 while ((bytesRead = is.read(dataBuffer, 0, 1024)) != -1) {
  digest.update(dataBuffer, 0, bytesRead);
  os.write(dataBuffer, 0, bytesRead);
String checksum = byteArrayToHex(digest.digest());
  new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(tmpArchive)))) {
   try (OutputStream outputFileStream = new FileOutputStream(dest)) {
    IOUtils.copy(stream, outputFileStream);
origin: i2p/i2p.i2p

boolean ok = false;
try {
  in = new BufferedInputStream(new FileInputStream(content));
  MessageDigest md = sigType.getDigestInstance();
  out = new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(_file)), md);
  out.write(MAGIC_BYTES);
  out.write((byte) 0);
  long tot = 0;
  while (tot < contentLength) {
    int read = in.read(buf, 0, (int) Math.min(buf.length, contentLength - tot));
    if (read < 0)
      throw new EOFException();
  byte[] sha = md.digest();
  out.on(false);
  SimpleDataStructure hash = sigType.getHashInstance();
  throw ioe;
} finally {
  if (in != null) try { in.close(); } catch (IOException ioe) {}
  if (out != null) try { out.close(); } catch (IOException ioe) {}
  if (!ok)
origin: JesusFreke/smali

private void updateSignature(@Nonnull DexDataStore dataStore) throws IOException {
  MessageDigest md;
  try {
    md = MessageDigest.getInstance("SHA-1");
  } catch (NoSuchAlgorithmException ex) {
    throw new RuntimeException(ex);
  }
  byte[] buffer = new byte[4 * 1024];
  InputStream input = dataStore.readAt(HeaderItem.SIGNATURE_DATA_START_OFFSET);
  int bytesRead = input.read(buffer);
  while (bytesRead >= 0) {
    md.update(buffer, 0, bytesRead);
    bytesRead = input.read(buffer);
  }
  byte[] signature = md.digest();
  if (signature.length != HeaderItem.SIGNATURE_SIZE) {
    throw new RuntimeException("unexpected digest write: " + signature.length + " bytes");
  }
  // write signature
  OutputStream output = dataStore.outputAt(HeaderItem.SIGNATURE_OFFSET);
  output.write(signature);
  output.close();
}
origin: org.apache.hadoop/hadoop-hdfs

if (getChecksum) {
 digester = MD5Hash.getDigester();
 stream = new DigestInputStream(stream, digester);
       + " with file downloaded from " + url);
    FileOutputStream fos = new FileOutputStream(f);
    outputStreams.add(fos);
    streamPathMap.put(fos, f);
  num = stream.read(buf);
  if (num > 0) {
   received += num;
   for (FileOutputStream fos : outputStreams) {
    fos.write(buf, 0, num);
     xferSec, xferKb / xferSec));
} finally {
 stream.close();
 for (FileOutputStream fos : outputStreams) {
  long flushStartTime = Time.monotonicNow();
  fos.getChannel().force(true);
  fos.close();
  double writeSec = Math.max(((float)
 MD5Hash computedDigest = new MD5Hash(digester.digest());
origin: jenkinsci/jenkins

public static String getDigestOf(@Nonnull InputStream source) throws IOException {
  try {
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    DigestInputStream in = new DigestInputStream(source, md5);
    return toHexString(md5.digest());
  } catch (NoSuchAlgorithmException e) {
    throw new IOException("MD5 not installed",e);    // impossible
  } finally {
    source.close();
origin: org.apache.ant/ant

try {
  for (Map.Entry<File, Object> e : includeFileMap.entrySet()) {
    messageDigest.reset();
    File src = e.getKey();
    if (!isCondition) {
    DigestInputStream dis = new DigestInputStream(fis,
                           messageDigest);
    while (dis.read(buf, 0, readBufferSize) != -1) {
    dis.close();
    fis.close();
    fis = null;
    byte[] fileDigest = messageDigest.digest();
    if (totalproperty != null) {
      allDigests.put(src, fileDigest);
    messageDigest.reset();
    for (File src : keyArray) {
      messageDigest.update(digest);
      messageDigest.update(fileName.getBytes());
    String totalChecksum = createDigestString(messageDigest.digest());
    getProject().setNewProperty(totalproperty, totalChecksum);
origin: org.nuxeo.ecm.core/nuxeo-core-api

protected String storeAndDigest(InputStream in, OutputStream out) throws IOException {
  MessageDigest digest;
  try {
    digest = MessageDigest.getInstance(getDigestAlgorithm());
  } catch (NoSuchAlgorithmException e) {
    throw (IOException) new IOException().initCause(e);
  }
  int size = in.available();
  if (size == 0) {
    size = MAX_BUF_SIZE;
  } else if (size < MIN_BUF_SIZE) {
    size = MIN_BUF_SIZE;
  } else if (size > MAX_BUF_SIZE) {
    size = MAX_BUF_SIZE;
  }
  byte[] buf = new byte[size];
  /*
   * Copy and digest.
   */
  int n;
  while ((n = in.read(buf)) != -1) {
    digest.update(buf, 0, n);
    out.write(buf, 0, n);
  }
  out.flush();
  return toHexString(digest.digest());
}
origin: org.apache.flink/flink-runtime

@Override
public int read() throws IOException {
  if (this.bytesReceived == this.bytesToReceive) {
    return -1;
  }
  final int read = this.wrappedInputStream.read();
  if (read < 0) {
    throwEOFException();
  }
  ++this.bytesReceived;
  if (this.md != null) {
    this.md.update((byte) read);
    if (this.bytesReceived == this.bytesToReceive) {
      final byte[] computedKey = this.md.digest();
      if (!Arrays.equals(computedKey, this.blobKey.getHash())) {
        this.wrappedOutputStream.write(RETURN_ERROR);
        throw new IOException("Detected data corruption during transfer");
      }
      this.wrappedOutputStream.write(RETURN_OKAY);
    }
  }
  return read;
}
origin: hs-web/hsweb-framework

    return fileStream.read();
}; FileOutputStream os = new FileOutputStream(fileAbsName)) {
  int remainBytes = fileSize = proxyStream.available();
  byte[] buff = new byte[remainBytes > 1024 * 10 ? 1024 * 10 : remainBytes];
  int bytes;
  logger.info("开始写出文件:{}到:{}, size: {} bytes", fileName, fileAbsName, fileSize);
  while (remainBytes > 0) {
    bytes = proxyStream.read(buff, 0, remainBytes > buff.length ? buff.length : remainBytes);
    os.write(buff, 0, bytes);
    remainBytes -= bytes;
    logger.info("写出文件:{}:{},剩余数据量: {} bytes", fileName, fileAbsName, remainBytes);
String md5 = Hex.encodeHexString(digest.digest());
origin: stackoverflow.com

  hash = new BASE64Encoder().encode(MessageDigest.getInstance("SHA-1").digest((keys.get("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes()));
} catch (NoSuchAlgorithmException ex) {
  ex.printStackTrace();
socket.getInputStream().read(b);
return b;
baos.write(SINGLE_FRAME_UNMASKED);
baos.write(msg.length);
baos.write(msg);
baos.flush();
baos.close();
convertAndPrint(baos.toByteArray());
java.securityMessageDigest

Javadoc

Uses a one-way hash function to turn an arbitrary number of bytes into a fixed-length byte sequence. The original arbitrary-length sequence is the message, and the fixed-length byte sequence is the digest or message digest.

Sample Code

The basic pattern to digest an java.io.InputStream looks like this:

 
MessageDigest digester = MessageDigest.getInstance("MD5"); 
byte[] bytes = new byte[8192]; 
int byteCount; 
while ((byteCount = in.read(bytes)) > 0) { 
digester.update(bytes, 0, byteCount); 
} 
byte[] digest = digester.digest(); 

That is, after creating or resetting a MessageDigest you should call #update(byte[],int,int) for each block of input data, and then call #digestto get the final digest. Note that calling digest resets the MessageDigest. Advanced users who want partial digests should clone their MessageDigest before calling digest.

This class is not thread-safe.

Most used methods

  • digest
    Computes and stores the final hash value for this MessageDigest. After the digest is computed the re
  • getInstance
    Returns a new instance of MessageDigest that utilizes the specified algorithm from the specified pro
  • update
    Updates this MessageDigest using the given byte[].
  • reset
    Puts this MessageDigest back in an initial state, such that it is ready to compute a one way hash va
  • isEqual
    Indicates whether to digest are equal by performing a simply byte-per-byte compare of the two digest
  • clone
    Returns a clone if the implementation is cloneable.
  • getAlgorithm
    Returns the name of the algorithm of this MessageDigest.
  • getDigestLength
    Returns the engine digest length in bytes. If the implementation does not implement this function or
  • toString
    Returns a string containing a concise, human-readable description of this MessageDigest including th
  • getProvider
    Returns the provider associated with this MessageDigest.
  • engineDigest
  • engineGetDigestLength
  • engineDigest,
  • engineGetDigestLength,
  • engineReset,
  • engineUpdate,
  • <init>

Popular in Java

  • Parsing JSON documents to java classes using gson
  • setScale (BigDecimal)
  • onRequestPermissionsResult (Fragment)
  • scheduleAtFixedRate (Timer)
  • FileNotFoundException (java.io)
    Thrown when a file specified by a program cannot be found.
  • Thread (java.lang)
    A thread is a thread of execution in a program. The Java Virtual Machine allows an application to ha
  • MessageDigest (java.security)
    Uses a one-way hash function to turn an arbitrary number of bytes into a fixed-length byte sequence.
  • BitSet (java.util)
    The BitSet class implements abit array [http://en.wikipedia.org/wiki/Bit_array]. Each element is eit
  • Executors (java.util.concurrent)
    Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory,
  • SAXParseException (org.xml.sax)
    Encapsulate an XML parse error or warning.> This module, both source code and documentation, is in t
  • CodeWhisperer alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now