Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Is there any method to generate MD5 hash of a string in Java?
I am looking to use java to get the md5 checksum of a file. I was really surprised but I haven't been able to find anything that shows how (and the best way) to get the md5 checksum of a file. Any ideas on how to go forward? Thanks.
I'm looking for a hash function that: Hashes textual strings well (e.g. few collisions) Is written in Java, and widely used Bonus: works on several fields (instead of me concatenating them and applying the hash on the concatenated string) Bonus: Has a 128-bit variant. Bonus: Not CPU intensive.
My goal is to authenticate to the database using a JDBC/Hibernate in a secure manner, without storing passwords in plain text. Code examples appreciated. I'm already using waffle to authenticate the user so if there was some way to use the credentials that waffle obtained from the user, and forward those to the DB, that would be good. Two questions: What is the recommended way to do multi ho...
I am looking for a way to compute SHA-1 checksums of very large files without having to fully load them into memory at once. I don't know the details of the SHA-1 implementation and therefore would like to know if it is even possible to do that. If you know the SAX XML parser, then what I look for would be something similar: Computing the SHA-1 checksum by only always loading a small part i...
What Java library should I be using to Hash passwords for storage in a database? I was hoping to just take the plain text password, add a random salt, then store the salt and the hashed password in the database. Then when a user wanted to log in, I could just take their submitted password, add the random salt from their account information, hash it and see if it equates to the stored hash pas...
To save a file i defined the following method public int encrypt(String fileName, String password) { return (fileName.concat(password)).hashCode(); } This returns a hashvalue that is stored in a file. Whenever the user wants to access the file, he enters the password, and if the same hash is generated, he can access the file. I suppose this isn't really safe, but how safe it is? How high...
I am migrating my PHP code to Google App Engine - Java. So I need an equivalent of PHP's crypt function in Java, since I have stored all the passwords of registered users using crypt in my DB. Edit 1: Here is my php code for encrypting passwords : $password = "test123"; $pwd = crypt($password,$password); echo $pwd; Output is (On Windows as well as a linux based server on HostMonser...
I'm looking for a way of getting an SHA-1 checksum with a Java byte array as the message Should I use a third party tool or is there something built in to the JVM that can help?
I'm trying to keep track of a set of files, which may have the same name and metadata. I'd like to use a hash to differentiate and use it as a unique ID, but I'm not sure which one to use? The files are relatively small (in the 100 kb range) and I'd like to be able to hash that in less than 10 seconds. Which hash (that comes built in in Java 1.5) would best suite my needs?
What's the most efficient way to identify a binary file? I would like to extract some kind of signature from a binary file and use it to compare it with others. The brute-force approach would be to use the whole file as a signature, which would take too long and too much memory. I'm looking for a smarter approach to this problem, and I'm willing to sacrifice a little accuracy (but not too much...
I want to encrypt and decrypt a password in Java and store into database in the form of encrypted. It will great if it is open source. Any suggestions / pointers ? Thanks, Amitm
I want to learn the (maximum) security features in android. Whatever security feature may be. Can you please guide me for that ? If you know security features please list it here. So that i can learn it very well. So far i have gone through : http://developer.android.com/guide/topics/security/security.html http://www.androidauthority.com/ Thanks, Kartik
I am working on a java application and would like to save password locally on a file. I am not sure how to achieve this, any help would be appreciated.
I have a login database, from my Android client I have to pass the password in a secure manner. I want to implement a login screen which is capable of doing encryption. How to implement the security encryption in my application?
I want to resemble the typical "confirmation of account" procedure seen in multiple websites. When a user registers an email is sent to him with a confirmation link. Once the user goes to that confirmation link its account gets confirmed. Don't worry about the email sending process. The thing is that I need to generate a URL to which the user can then enter to get his new account confirmed. Thi...
By looking around here as well as the internet in general, I have found Bouncy Castle. I want to use Bouncy Castle (or some other freely available utility) to generate a SHA-256 Hash of a String in Java. Looking at their documentation I can't seem to find any good examples of what I want to do. Can anybody here help me out?
Grails 1.1 onwards has 'encodeAsMD5' available on Strings -- is there a way to provide a salt for the function? Typical usage: ${myString.encodeAsMD5()} Another option would be to use the Apache DigestUtils class. I'm not using this to do password hashing -- instead, I'm using it for a verification mechanism to determine when a request was created and how much time elapsed when the respons...
The MessageDigest class implements the SHA-1 algorithm (among many others). The SHA-1 algorithm allows one to use different "seeds" or initial digests. See SHA-1 Psuedocode The algorithm initializes variables, or the seed: Initialize variables: h0 = 0x67452301 h1 = 0xEFCDAB89 h2 = 0x98BADCFE h3 = 0x10325476 h4 = 0xC3D2E1F0 However the MessageDigest class, as described in the Online Jav...
writing a Java EE 6 application i need some help using the DatabaseServerLoginModule with md5 hashing. Setup: login-config.xml: <application-policy name = "app"> <authentication> <login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule" flag = "required"> <module-option name = "dsJndiName">java:/MySQLDS</module-option> ...
I am using Postgresql,hibernate and Java and I need to store a password. Can someone suggest me how to encrypt the password with md5. Else is there a better way to store secure password in the database Thanks
  /*
   * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.security;
 
 import java.util.*;
 import java.lang.*;
 
This MessageDigest class provides applications the functionality of a message digest algorithm, such as MD5 or SHA. Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value.

A MessageDigest object starts out initialized. The data is processed through it using the update methods. At any point reset can be called to reset the digest. Once all the data to be updated has been updated, one of the digest methods should be called to complete the hash computation.

The digest method can be called once for a given number of updates. After digest has been called, the MessageDigest object is reset to its initialized state.

Implementations are free to implement the Cloneable interface. Client applications can test cloneability by attempting cloning and catching the CloneNotSupportedException:

 MessageDigest md = MessageDigest.getInstance("SHA");

 try {
     md.update(toChapter1);
     MessageDigest tc1 = md.clone();
     byte[] toChapter1Digest = tc1.digest();
     md.update(toChapter2);
     ...etc.
 } catch (CloneNotSupportedException cnse) {
     throw new DigestException("couldn't make digest of partial content");
 }
 

Note that if a given implementation is not cloneable, it is still possible to compute intermediate digests by instantiating several instances, if the number of digests is known in advance.

Note that this class is abstract and extends from MessageDigestSpi for historical reasons. Application developers should only take notice of the methods defined in this MessageDigest class; all the methods in the superclass are intended for cryptographic service providers who wish to supply their own implementations of message digest algorithms.

Author(s):
Benjamin Renaud
See also:
DigestInputStream
DigestOutputStream
 
 
 public abstract class MessageDigest extends MessageDigestSpi {
 
     private String algorithm;
 
     // The state of this digest
     private static final int INITIAL = 0;
     private static final int IN_PROGRESS = 1;
     private int state = ;
 
    // The provider
    private Provider provider;

    
Creates a message digest with the specified algorithm name.

Parameters:
algorithm the standard name of the digest algorithm. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
    protected MessageDigest(String algorithm) {
        this. = algorithm;
    }

    
Returns a MessageDigest object that implements the specified digest algorithm.

This method traverses the list of registered security Providers, starting with the most preferred Provider. A new MessageDigest object encapsulating the MessageDigestSpi implementation from the first Provider that supports the specified algorithm is returned.

Note that the list of registered providers may be retrieved via the Security.getProviders() method.

Parameters:
algorithm the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
Returns:
a Message Digest object that implements the specified algorithm.
Throws:
NoSuchAlgorithmException if no Provider supports a MessageDigestSpi implementation for the specified algorithm.
See also:
Provider
    public static MessageDigest getInstance(String algorithm)
    throws NoSuchAlgorithmException {
        try {
            Object[] objs = Security.getImpl(algorithm"MessageDigest",
                                             (String)null);
            if (objs[0] instanceof MessageDigest) {
                MessageDigest md = (MessageDigest)objs[0];
                md.provider = (Provider)objs[1];
                return md;
            } else {
                MessageDigest delegate =
                    new Delegate((MessageDigestSpi)objs[0], algorithm);
                delegate.provider = (Provider)objs[1];
                return delegate;
            }
        } catch(NoSuchProviderException e) {
            throw new NoSuchAlgorithmException(algorithm + " not found");
        }
    }

    
Returns a MessageDigest object that implements the specified digest algorithm.

A new MessageDigest object encapsulating the MessageDigestSpi implementation from the specified provider is returned. The specified provider must be registered in the security provider list.

Note that the list of registered providers may be retrieved via the Security.getProviders() method.

Parameters:
algorithm the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
provider the name of the provider.
Returns:
a MessageDigest object that implements the specified algorithm.
Throws:
NoSuchAlgorithmException if a MessageDigestSpi implementation for the specified algorithm is not available from the specified provider.
NoSuchProviderException if the specified provider is not registered in the security provider list.
java.lang.IllegalArgumentException if the provider name is null or empty.
See also:
Provider
    public static MessageDigest getInstance(String algorithmString provider)
    {
        if (provider == null || provider.length() == 0)
            throw new IllegalArgumentException("missing provider");
        Object[] objs = Security.getImpl(algorithm"MessageDigest"provider);
        if (objs[0] instanceof MessageDigest) {
            MessageDigest md = (MessageDigest)objs[0];
            md.provider = (Provider)objs[1];
            return md;
        } else {
            MessageDigest delegate =
                new Delegate((MessageDigestSpi)objs[0], algorithm);
            delegate.provider = (Provider)objs[1];
            return delegate;
        }
    }

    
Returns a MessageDigest object that implements the specified digest algorithm.

A new MessageDigest object encapsulating the MessageDigestSpi implementation from the specified Provider object is returned. Note that the specified Provider object does not have to be registered in the provider list.

Parameters:
algorithm the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
provider the provider.
Returns:
a MessageDigest object that implements the specified algorithm.
Throws:
NoSuchAlgorithmException if a MessageDigestSpi implementation for the specified algorithm is not available from the specified Provider object.
java.lang.IllegalArgumentException if the specified provider is null.
Since:
1.4
See also:
Provider
    public static MessageDigest getInstance(String algorithm,
                                            Provider provider)
        throws NoSuchAlgorithmException
    {
        if (provider == null)
            throw new IllegalArgumentException("missing provider");
        Object[] objs = Security.getImpl(algorithm"MessageDigest"provider);
        if (objs[0] instanceof MessageDigest) {
            MessageDigest md = (MessageDigest)objs[0];
            md.provider = (Provider)objs[1];
            return md;
        } else {
            MessageDigest delegate =
                new Delegate((MessageDigestSpi)objs[0], algorithm);
            delegate.provider = (Provider)objs[1];
            return delegate;
        }
    }

    
Returns the provider of this message digest object.

Returns:
the provider of this message digest object
    public final Provider getProvider() {
        return this.;
    }

    
Updates the digest using the specified byte.

Parameters:
input the byte with which to update the digest.
    public void update(byte input) {
        engineUpdate(input);
         = ;
    }

    
Updates the digest using the specified array of bytes, starting at the specified offset.

Parameters:
input the array of bytes.
offset the offset to start from in the array of bytes.
len the number of bytes to use, starting at offset.
    public void update(byte[] inputint offsetint len) {
        if (input == null) {
            throw new IllegalArgumentException("No input buffer given");
        }
        if (input.length - offset < len) {
            throw new IllegalArgumentException("Input buffer too short");
        }
        engineUpdate(inputoffsetlen);
         = ;
    }

    
Updates the digest using the specified array of bytes.

Parameters:
input the array of bytes.
    public void update(byte[] input) {
        engineUpdate(input, 0, input.length);
         = ;
    }

    
Update the digest using the specified ByteBuffer. The digest is updated using the input.remaining() bytes starting at input.position(). Upon return, the buffer's position will be equal to its limit; its limit will not have changed.

Parameters:
input the ByteBuffer
Since:
1.5
    public final void update(ByteBuffer input) {
        if (input == null) {
            throw new NullPointerException();
        }
        engineUpdate(input);
         = ;
    }

    
Completes the hash computation by performing final operations such as padding. The digest is reset after this call is made.

Returns:
the array of bytes for the resulting hash value.
    public byte[] digest() {
        /* Resetting is the responsibility of implementors. */
        byte[] result = engineDigest();
         = ;
        return result;
    }

    
Completes the hash computation by performing final operations such as padding. The digest is reset after this call is made.

Parameters:
buf output buffer for the computed digest
offset offset into the output buffer to begin storing the digest
len number of bytes within buf allotted for the digest
Returns:
the number of bytes placed into buf
Throws:
DigestException if an error occurs.
    public int digest(byte[] bufint offsetint lenthrows DigestException {
        if (buf == null) {
            throw new IllegalArgumentException("No output buffer given");
        }
        if (buf.length - offset < len) {
            throw new IllegalArgumentException
                ("Output buffer too small for specified offset and length");
        }
        int numBytes = engineDigest(bufoffsetlen);
         = ;
        return numBytes;
    }

    
Performs a final update on the digest using the specified array of bytes, then completes the digest computation. That is, this method first calls update(input), passing the input array to the update method, then calls digest().

Parameters:
input the input to be updated before the digest is completed.
Returns:
the array of bytes for the resulting hash value.
    public byte[] digest(byte[] input) {
        update(input);
        return digest();
    }

    
Returns a string representation of this message digest object.
    public String toString() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream p = new PrintStream(baos);
        p.print(+" Message Digest from "+.getName()+", ");
        switch () {
        case :
            p.print("<initialized>");
            break;
        case :
            p.print("<in progress>");
            break;
        }
        p.println();
        return (baos.toString());
    }

    
Compares two digests for equality. Does a simple byte compare.

Parameters:
digesta one of the digests to compare.
digestb the other digest to compare.
Returns:
true if the digests are equal, false otherwise.
    public static boolean isEqual(byte digesta[], byte digestb[]) {
        if (digesta.length != digestb.length)
            return false;
        for (int i = 0; i < digesta.lengthi++) {
            if (digesta[i] != digestb[i]) {
                return false;
            }
        }
        return true;
    }

    
Resets the digest for further use.
    public void reset() {
        engineReset();
         = ;
    }

    
Returns a string that identifies the algorithm, independent of implementation details. The name should be a standard Java Security name (such as "SHA", "MD5", and so on). See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.

Returns:
the name of the algorithm
    public final String getAlgorithm() {
        return this.;
    }

    
Returns the length of the digest in bytes, or 0 if this operation is not supported by the provider and the implementation is not cloneable.

Returns:
the digest length in bytes, or 0 if this operation is not supported by the provider and the implementation is not cloneable.
Since:
1.2
    public final int getDigestLength() {
        int digestLen = engineGetDigestLength();
        if (digestLen == 0) {
            try {
                MessageDigest md = (MessageDigest)clone();
                byte[] digest = md.digest();
                return digest.length;
            } catch (CloneNotSupportedException e) {
                return digestLen;
            }
        }
        return digestLen;
    }

    
Returns a clone if the implementation is cloneable.

Returns:
a clone if the implementation is cloneable.
Throws:
java.lang.CloneNotSupportedException if this is called on an implementation that does not support Cloneable.
    public Object clone() throws CloneNotSupportedException {
        if (this instanceof Cloneable) {
            return super.clone();
        } else {
            throw new CloneNotSupportedException();
        }
    }
    /*
     * The following class allows providers to extend from MessageDigestSpi
     * rather than from MessageDigest. It represents a MessageDigest with an
     * encapsulated, provider-supplied SPI object (of type MessageDigestSpi).
     * If the provider implementation is an instance of MessageDigestSpi,
     * the getInstance() methods above return an instance of this class, with
     * the SPI object encapsulated.
     *
     * Note: All SPI methods from the original MessageDigest class have been
     * moved up the hierarchy into a new class (MessageDigestSpi), which has
     * been interposed in the hierarchy between the API (MessageDigest)
     * and its original parent (Object).
     */
    static class Delegate extends MessageDigest {
        // The provider implementation (delegate)
        private MessageDigestSpi digestSpi;
        // constructor
        public Delegate(MessageDigestSpi digestSpiString algorithm) {
            super(algorithm);
            this. = digestSpi;
        }

        
Returns a clone if the delegate is cloneable.

Returns:
a clone if the delegate is cloneable.
Throws:
java.lang.CloneNotSupportedException if this is called on a delegate that does not support Cloneable.
        public Object clone() throws CloneNotSupportedException {
            if ( instanceof Cloneable) {
                MessageDigestSpi digestSpiClone =
                    (MessageDigestSpi).clone();
                // Because 'algorithm', 'provider', and 'state' are private
                // members of our supertype, we must perform a cast to
                // access them.
                MessageDigest that =
                    new Delegate(digestSpiClone,
                                 ((MessageDigest)this).);
                that.provider = ((MessageDigest)this).;
                that.state = ((MessageDigest)this).;
                return that;
            } else {
                throw new CloneNotSupportedException();
            }
        }
        protected int engineGetDigestLength() {
            return .engineGetDigestLength();
        }
        protected void engineUpdate(byte input) {
            .engineUpdate(input);
        }
        protected void engineUpdate(byte[] inputint offsetint len) {
            .engineUpdate(inputoffsetlen);
        }
        protected void engineUpdate(ByteBuffer input) {
            .engineUpdate(input);
        }
        protected byte[] engineDigest() {
            return .engineDigest();
        }
        protected int engineDigest(byte[] bufint offsetint len)
            throws DigestException {
                return .engineDigest(bufoffsetlen);
        }
        protected void engineReset() {
            .engineReset();
        }
    }
New to GrepCode? Check out our FAQ X