What does update method of MessageDigest do and wh

2020-05-27 11:06发布

问题:

Following is a code that will encrypts the user String :

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;
import java.io.*;

class Encrypter {
public synchronized String encrypt(String plainText) throws Exception {
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA");
    }catch(Exception exc) {
        throw new Exception(exc.getMessage());
     }

     try {
        md.update(plainText.getBytes("UTF-8"));
     }catch(Exception exc) {
        throw new Exception(exc.getMessage());
      }

      byte raw[] = md.digest();
      String hash = (new BASE64Encoder()).encode(raw);
      return hash;
}
public static void main(String args[]) {
    try {
        Encrypter encrypter = new Encrypter();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String userInput = br.readLine();
        String encryptedPassword = encrypter.encrypt(userInput);
        System.out.println(encryptedPassword);
    } catch(Exception exc) {
        System.out.println(exc);
      }
}
}

When i compile the code i get the these warnings :

Encrypter.java:4: warning: BASE64Encoder is internal proprietary API and may be removed in a future release
import sun.misc.BASE64Encoder;
           ^
Encrypter.java:23: warning: BASE64Encoder is internal proprietary API and may be removed in a future release
              String hash = (new BASE64Encoder()).encode(raw);
                                 ^
2 warnings

Is there any other method to encrypt strings in java ?

What does the method update of class MessageDigest do ? i.e What does the statement md.update(plainText.getBytes("UTF-8")); do ?

What is a BASE64Encoder class ? I couldn't find it's DOC

回答1:

  1. First of all, you're not performing any encryption. You're computing a one-way hash or digest of your input. This hash can be later used to verify the integrity of the message. See Hashing, SHA1 and MessageDigest.

  2. Base64 encoding is a method of representing binary data in ASCII. This is often desirable because not all data storage and transmission mechanisms support raw binary. For example, if you want to transfer your computed digest via an http query string parameter, you'll want to encode it as Base64. Also, saving or printing raw binary to the console will produce a stream of funky characters which may be outside of the printable range, and may also produce beeps from your PC speaker!

  3. The Base64Encoder you're using comes from the sun.misc package and should NEVER be used. This is internal Sun JVM code which may or may not be available in the future. That also explains why you're weren't able to find any javadoc.

  4. Fortunately, several free and open Base64 encoders and decoders exist. Apache Commons Codec is a widely used and stable library which contains several codecs include Base64.

  5. md.update(plainText.getBytes("UTF-8")) updates the input to the digest. Calling digest performs a final update and computes the digest of the input. See javadoc of md.digest and md.update



回答2:

Have a look at Apache Commons Codec: https://commons.apache.org/codec/

E.g.: https://commons.apache.org/codec/api-release/org/apache/commons/codec/digest/DigestUtils.html



回答3:

While old post here is an updated answer. Java 8's Base64.

Java 8 Base64 Documents



回答4:

For Base64 encryption and decryption this warning clearly says that it does not encourage the use of Sun implementation of Base64Encoder and gives a warning that the implementation may be removed in future releases, what we can do is to switch to other implementation of Base64 encoder. We can use Commons Codec library for Base64 Encoder. Following is an example:

1. Add Commons Codec library in classpath of your project
2. Add import statement for Base64 Class.

import org.apache.commons.codec.binary.Base64;

3. Encrypt your data

String testString = "Hello World";
byte[] encodedBytes = Base64.encodeBase64(testString.getBytes());
// Get encoded string
String encodedString = new String(encodedBytes);
// Get decoded string back
String decodedString = new String(Base64.decodeBase64(encodedBytes));

After using Commons codec library, you should not see above warning again.



回答5:

To build off of bullet 5 from Sahil Muthoo's excellent answer, below is an deeper look into the source code.

By default, the update method simply appends the input byte array to the current tempArray of the MessageDigestSpi abstract class.

The MessageDigest class extends the MessageDigestSpi class. Then MessageDigest.update is called the method MessageDigestSpi.engineUpdate is called, which can be found from investigating the source code:

MessageDigest.java (source code)

196:   /**
197:    * Updates the digest with the byte.
...
200:    */
201:   public void update(byte input)
202:   {
203:     engineUpdate(input);
204:   }
205: 
206:   /**
207:    * Updates the digest with the bytes from the array starting from the
208:    * specified offset and using the specified length of bytes.
209:    * 
210:    * @param input
211:    *          bytes to update the digest with.
212:    * @param offset
213:    *          the offset to start at.
214:    * @param len
215:    *          length of the data to update with.
216:    */
217:   public void update(byte[] input, int offset, int len)
218:   {
219:     engineUpdate(input, offset, len);
220:   }
...
227:   public void update(byte[] input)
228:   {
229:     engineUpdate(input, 0, input.length);
230:   }
...
238:   public void update (ByteBuffer input)
239:   {
240:     engineUpdate (input);
241:   }

MessageDigestSpi.engineUpdate is an abstract method that must be implemented by extending classes as seen below:

MessageDigestSpi.java (source code)

42:    /**
43:     * Updates this {@code MessageDigestSpi} using the given {@code byte}.
44:     *
45:     * @param input
46:     *            the {@code byte} to update this {@code MessageDigestSpi} with.
47:     * @see #engineReset()
48:     */
49:    protected abstract void engineUpdate(byte input);
50:    /**
51:     * Updates this {@code MessageDigestSpi} using the given {@code byte[]}.
52:     *
53:     * @param input
54:     *            the {@code byte} array.
55:     * @param offset
56:     *            the index of the first byte in {@code input} to update from.
57:     * @param len
58:     *            the number of bytes in {@code input} to update from.
59:     * @throws IllegalArgumentException
60:     *             if {@code offset} or {@code len} are not valid in respect to
61:     *             {@code input}.
62:     */
63:    protected abstract void engineUpdate(byte[] input, int offset, int len);
64:    /**
65:     * Updates this {@code MessageDigestSpi} using the given {@code input}.
66:     *
67:     * @param input
68:     *            the {@code ByteBuffer}.
69:     */
70:    protected void engineUpdate(ByteBuffer input) {
71:        if (!input.hasRemaining()) {
72:            return;
73:        }
74:        byte[] tmp;
75:        if (input.hasArray()) {
76:            tmp = input.array();
77:            int offset = input.arrayOffset();
78:            int position = input.position();
79:            int limit = input.limit();
80:            engineUpdate(tmp, offset+position, limit - position);
81:            input.position(limit);
82:        } else {
83:            tmp = new byte[input.limit() - input.position()];
84:            input.get(tmp);
85:            engineUpdate(tmp, 0, tmp.length);
86:        }
87:    }